关于共享内存,子进程返回的问题。
父进程对共享内存的数据进行操作,子进程读数据,读到*p=99的时候就退出。但是问题是发现,父进程退出之后,子进程无法退出。但是子进程的child is done都打印出来了啊.为何啊?
#include <sys/shm.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
static int *getaddr(void)
{
key_t key;
int shmid, *p;
(void)close(open("shmseg", O_WRONLY | O_CREAT, 0));
key = ftok("shmseg", 1);
shmid = shmget(key, sizeof(int), IPC_CREAT);
p = shmat(shmid, NULL, 0);
return p;
}
运行结果:
The address of share memory at son is 16941787.
child saw 1
The address of share memory at parent is 16941787.
child saw 2
child saw 3
parent exit
[root@localhost Unix_work_test]# child saw 99
child is done
int main(void)
{
pid_t pid;
if ((pid = fork()) == 0) {
int *p, prev = 0;
p = getaddr();
printf("The address of share memory at son is %d.\n");
*p=1;
while (*p != 99)
if (prev != *p) {
printf("child saw %d\n", *p);
prev = *p;
}
printf("child is done\n");
exit(0);
}
else {
int *p;
p = getaddr();
printf("The address of share memory at parent is %d.\n");
for (*p = 1; *p < 4; (*p)++)
sleep(1);
*p = 99;
}
printf("parent exit\n");
exit(0);
}