如何使子进程使用共享内存

时间:2019-04-16 04:41:01

标签: c fork shared-memory

我正在尝试将共享内存与子进程一起使用。我应该通过一个函数附加共享内存。但是,当我这样做时,子进程不使用共享内存,而是在其自己的地址空间中使用内存。有什么我想念的吗?

(背景),应该通过输入数字,用该数字填充共享内存并让孩子乘以该数字的两倍来运行程序。

当我将内存附加到主函数中而不是通过函数附加时,一切正常。

const int numIntegers = argNUM - 1; // number of integers entered by user
const int shareSize = sizeof (int) * (numIntegers); // share memory size

int shmUniqueID; // id for shared memory of pid's
int *shmUniqueArr; // memory for unique pids   
int shmid; // id for shared memory of command line args 
int * shmArry; // shared memory for command line args    


requestMemory(&shmid, &shmUniqueID, shareSize); 

之所以在这里使用malloc是因为当我尝试填充 实际的共享内存,我会遇到分段错误。我认为 我需要为shmArry分配内存空间,然后尝试附加 它

shmArry = (int*) malloc(shareSize); // allocate shared memory of args
shmUniqueArr = (int*) malloc(shareSize); // allocate shared mem for ID's


attachMemory(shmid, shmArry);
attachMemory(shmUniqueID, shmUniqueArr); // attached memory

当我取消注释这些行并删除函数调用时,子进程将能够使用共享内存

 //    shmArry = (int *) shmat(shmid, NULL, 0);
 //    if (shmArry == (int *) - 1) {
 //        exit(EXIT_ERROR); // ASK
 //    }
 //    
 //    shmUniqueArr = (int *) shmat(shmUniqueID, NULL, 0);
 //    if (shmUniqueArr == (int *) - 1) {
 //        exit(EXIT_ERROR); // ASK
 //    }

父子进程

printf("%s", "Parent: attaches shared memory\n");
parentStart(numIntegers, argValue, shmArry);
createChildren(numIntegers, shmArry, pids, shmUniqueArr);
waitParent(numIntegers, pids, exitCodes); // Parent waits
parentExitOutput(shmUniqueArr, exitCodes, shmArry, numIntegers);

printf("%s", "Parent: Detaches shared memory\n");
detachMemory(shmUniqueArr);
detachMemory(shmArry);
printf("%s", "Parent: Removes shared memory\n");
removeMemory(shmUniqueID, shmUniqueArr);
removeMemory(shmid, shmArry);

attachMemory函数

void attachMemory(int shmid, int * sharedMem) {

    sharedMem = (int *) shmat(shmid, NULL, 0);
    if (sharedMem == (int *) - 1) {
        exit(EXIT_ERROR); 
    }    
}

程序在完成父级并更改了内存后,在父级中输出初始共享内存,在子级中输出初始和最终共享内存,并在父级中输出最终共享内存。 预期产量

 ...

 Parent: initial shared memory
 Shared Memory Value 1: 2
 Parent: forks (each) child process
 Parent: waits for (each) child....
   Child 1 starts
   Initial Shared Memory value
   Shared Memory Value 1: 2
   Final Shared Memory value
   Shared Memory Value 1: 4
   Child 1 exiting
 Parent: detects (each) child child completion....
 Parent: Displaying Unique ID's
 Unique ID 0 
 Parent: Displaying Exit Codes/Status
 Unique ID 0 exit code 0
 Parent: final shared memory
 Shared Memory Value 1: 1 **(should be 4)**
 ...

0 个答案:

没有答案