c - 从共享内存读取段错误

标签 c segmentation-fault fork shared-memory

我正在处理一个家庭作业问题,使用 fork() 和共享内存对象在 C 中编写 collat​​z 猜想的实现,在子进程中执行计算并在父进程中打印结果。我对 C 不是很熟悉,所以我学习了很多工具。使用 gdb,我在尝试访问父进程中的对象时发现了一个段错误。我正在使用这是我的代码:

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <math.h>

int main(int argc, const char* argv[])
{

const int SIZE  = 4096;
const char *name = "SM";
int shm_fd;
void  *ptr;

pid_t child;


if ((argc != 2) || (strtol(argv[1],NULL, 10) <= 0))
{
        printf("Invalid usage: requires 1 positive integer parameter\n");
        return -1;
}

child = fork();
if(child >=0 )
{
        if (child == 0)
        {
                shm_fd = shm_open(name, O_CREAT || O_RDWR, 0666);
                ftruncate(shm_fd, SIZE);
                ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
                int currentval = strtol(argv[1],NULL,10);
                sprintf(ptr,"%d",currentval);
                ptr++;/*  floor(log10(abs(currentval))) + 1;*/
                while (currentval > 1)
                {
                        sprintf(ptr, ", ");
                        ptr += 2;
                        if (currentval % 2 == 1)
                        {
                                currentval = currentval * 3 + 1;
                                sprintf(ptr, "%d", currentval);
                                ptr++;
                        }
                        else
                        {
                                currentval = currentval/2;
                                sprintf(ptr, "%d", currentval);
                                ptr++;
                        }
                }
                sprintf(ptr, "\n");
                ptr+= 1;
                return 0;
        }
        else
        {
                wait();

                shm_fd = shm_open(name, O_RDONLY, 0666);
                ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
                printf("%s\n",(char *)ptr);
                shm_unlink(name);
                return 0;
        }
}
else
{
        printf("error creating child process\n");
}
return 0;
}

我以前从未调试过段错误,因此非常欢迎任何建议。提前致谢。

最佳答案

我发现了问题。它执行的是逻辑或而不是按位或,因此创建了错误的文件描述符。

shm_fd = shm_open(名称, O_CREAT || O_RDWR, 0666);

应该是

shm_fd = shm_open(名称, O_CREAT | O_RDWR, 0666);

关于c - 从共享内存读取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086170/

相关文章:

更改目录时间/日期

c - 关于 fork() 之后的指针

c - 管道和 fork 问题 - 管道中的某些输入未正确清除

java - 在java中调用C函数

c - 为什么通过引用写入 bitfield-uint union 会产生错误的汇编指令?

c - 结构数组的动态分配

c - 使用 sscanf 时出现段错误

c - while 循环内出现段错误

C管道: Bad file descriptor

c - 用 C 宏定义常量变量