分段错误(核心转储) - 我的代码有什么问题

时间:2015-12-05 01:02:56

标签: c unix gcc segmentation-fault

有人知道为什么我收到消息"分段错误(核心转储)"?怎么了?在我看来,问题在于数组。我知道"分段错误"意味着我试图访问我无法访问的内存。

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, const char* argv[])
{
    int shmid;
    int i, j;
    int glos;
    pid_t pid;
    key_t key;
    long *wyniki;

    key = ftok("/home/sebastian", 2);

    shmid = shmget(key, 20 * sizeof(long), IPC_CREAT);

    if (shmid == -1) {
        printf("Error - New memory segment");
    }
    else {
        printf("My memory segment: %d\n", shmid);
        wyniki = (long*) shmat(shmid, 0, 0);

        for (i = 0; i < 5; i++) {
            wyniki[i] = 0;
        }

        // Creating new processes
        for (i = 0; i < 20; i++) {
            pid = fork();
            if (pid == 0) {
                srand48(time(NULL) + getpid());
                for (j = 0; j < 1000000; j++) {
                    glos = rand() % 5;
                    wyniki[glos] += 1;
                }
            }
            else {
                printf("ERROR - PROCESSES");
            }
        }
    }

return 0;
}

2 个答案:

答案 0 :(得分:4)

您创建了共享内存段而未正确设置权限位,因此您无法访问内存。

根据shmget() man page

   int shmget(key_t key, size_t size, int shmflg);
   ...
   In addition to the above flags, the least significant 9 bits of
   shmflg specify the permissions granted to the owner, group, and
   others.  These bits have the same format, and the same meaning, as
   the mode argument of open(2).  Presently, execute permissions are not
   used by the system.

您需要指定共享内存段的权限:

shmid=shmget(key, 20 * sizeof(long), IPC_CREAT | 0600);

或使用06400660或符号模式。

但首先您可能需要使用ipcrm删除现有细分。

答案 1 :(得分:0)

修复`过多的进程创建问题:

改变这个:

    // Creating new processes
    for (i = 0; i < 20; i++) {
        pid = fork();
        if (pid == 0) {
            srand48(time(NULL) + getpid());
            for (j = 0; j < 1000000; j++) {
                glos = rand() % 5;
                wyniki[glos] += 1;
            }
        }
        else {
            printf("ERROR - PROCESSES");
        }
    }

到此:

    // Creating new processes
    for (i = 0; i < 20; i++) 
    {
        pid = fork();
        if (pid == 0) 
        { // child process
            srand48(time(NULL) + getpid());
            for (j = 0; j < 1000000; j++) 
            {
                glos = rand() % 5;
                wyniki[glos] += 1;
            }
            exit();
        }

        else if( 0 > pid)
        { // error occurred
            perror( "fork() failed" );
            printf("ERROR - PROCESSES\n");
        }

        //else
        //{ // parent process
        //    ; 
        //}
    } // end: for 20 child processes