c - 段错误(核心转储)-我的代码出了什么问题

标签 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;
}

最佳答案

您创建共享内存段时没有正确设置权限位,因此您无权访问该内存。

根据 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 删除现有段。

关于c - 段错误(核心转储)-我的代码出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34100020/

相关文章:

linux - Bash - 如何在这种情况下调用函数

linux - 在 unix 中列出文件并将输出保存在变量中(获取特定扩展名的最旧文件)

Bash 脚本删除文本文件中的所有行,直到出现字符串

android - 在 C 中通过 strtok 实现拆分字符串 - 段错误(核心转储)

c - C-接受已知大小但未知类型的参数

c - HTTP 服务器和 CGI​​ 处理

正确输出后打印随机符号的C程序

c++ - 错误 : anachronistic old-style base class initializer

c++ - 为什么 string::append 操作表现奇怪?

C-动态函数调用