我在编程中创建了几个子进程,所以我决定 创建一个共享内存数组,如下所示:
void makeSharedArr(int sharedId, int ** sharedArr, int numArgs)
{
sharedId = shmget(IPC_PRIVATE, numArgs*sizeof(int), 0666 );
if (sharedId < 0)
{
perror("error allocating shared memory...exiting\n");
exit(ERROR);
}
else
{
write(1,"allocated memory...\n",20);
}
*sharedArr = (int *) shmat(sharedId, NULL, 0);
if((long) sharedArr == -1)
{
perror("error attaching the shared memory...exiting\n");
exit(ERROR);
}
else
{
write(1,"attached the shared memory...\n",30);
}
}
在我操作一些工作之后,共享阵列成功分离,但是我在删除父函数中的内存时遇到了问题:
void parent(int *arr, int sharedId, int numArgs)
{
//wait for all children
while(wait(NULL) > 0) {/*..waiting..*/}
// print array
printf("array in parent: ");
printArr(arr, numArgs);
// detach and mark memory to be free
if(shmdt((void *) arr) == 0)
{
write(1, "memory block was detached...\n",29);
}
else
{
write(1,"error detaching memory block...\n",32);
}
if(shmctl(sharedId, IPC_RMID, (struct shmid_ds *) NULL) == 0)
{
write(1, "memory block is now free...\n",28);
}
else
{
perror("error freeing memory\n");
//write(1,"error freeing memory...\n",24);
}
// notify that parent is exiting
printf("Parent exiting...\n");
}