fork()后无法从子进程检索mmap共享内存

时间:2013-11-22 22:36:35

标签: c multithreading fork mmap

更新:我无法实现这一目标并采取了不同的方法。问题是,正如@nos指出的那样,不是这个代码而是其他地方。 ArrayList在其实现中分配内存,这不是我们分配的共享内存的一部分。感谢您的回复。

原始问题:

我有一个叉子。我的目标是让子进程填充数据结构(db - 它是一个ArrayList - 外部实现),然后能够从父进程中读取该数据结构。目前,结果是seg错误,因为父进程中的数据结构为空。

以下是代码:

    static ArrayList *db;
    pid_t child_pid, pid;
int child_status;

//set up shared memory structure
db = mmap(NULL, 20000, PROT_READ | PROT_WRITE, 
                MAP_SHARED | MAP_ANONYMOUS, -1, 0);


child_pid = fork();
if(child_pid == 0) {

    //Some operations to initialize and populate db happen here. This works fine.


    //printAll(db, 1); //THIS would work. But I want to do this from the parent
    exit(0);

} else {
    //wait for child process to finish

        do {
            pid = wait(&child_status);

        } while(pid != child_pid);




    printAll(db, 1);//THIS IS WHERE IT SEGFAULTS, because db is not initialized - so it was never properly retrieved from mmap
    munmap(db, 20000); //fixed this



}

1 个答案:

答案 0 :(得分:1)

 munmap(db, 20000);

 printAll(db, 1);//T//THIS IS WHERE IT SEGFAULTS,

这并不特别令人惊讶,你在其上方的行上取消了映射。