父子进程共享内存问题
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
pid_t cpid;
int *data = NULL;
int fd;
fd = open ("/dev/zero", O_RDWR);
if (fd < 0) {
perror ("open /dev/zero");
exit(1);
}
data = (void *) mmap (0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
perror ("mmap");
exit(2);
}
*data = 0;
close (fd);
cpid = fork ();
if (cpid == 0)
{
for (;;)
{
sleep (1);
printf ("Child-0: %d\n", *data);
}
} else if (cpid > 0)
{
cpid = fork ();
if (cpid == 0)
{
for (;;)
{
sleep (1);
(*data) ;
printf ("Child-1: %d\n", *data);
}
} else if (cpid > 0)
{
for (;;)
{
sleep (1);
printf ("Parent-0: %d\n", *data);
}
}
}
munmap (data, 4096);
return 0;
}
关键词标签:进程共享,内存