在shmget函数中使用 IPC_PRIVATE的场合,发生在具有亲缘关系的进程间通信的场合。
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/shm.h>
struct st
{
sem_t mutex;
int value;
};
int main()
{
int id;
pid_t pt;
id = shmget(IPC_PRIVATE, sizeof(struct st), IPC_CREAT|0666);
if(id==-1)
{
printf("shmget fail\n");
return 1;
}
printf("shmid: %d\n", id);
//映射
struct st*p;
p = shmat(id, NULL, 0);
//初始化
sem_init(&(p->mutex),1,1);
p->value=0;
// fork
pt = fork();
if(pt<0)
{
shmdt(p);
shmctl(id, IPC_RMID, NULL);
return 3;
}
else if(pt==0) //子进程
{
while(1)
{
printf("child! ");
sem_wait( &(p->mutex));
if(p->value<100)
{
p->value++;
printf("plus: %d by %d\n", p->value, getpid());
}else
{
// shmctl(id, IPC_RMID, NULL);
sem_post( &(p->mutex));
// shmdt(p);
break;
}
sem_post( &(p->mutex));
}
}else
{
while(1)
{
printf("father! ");
sem_wait( &(p->mutex));
if(p->value<100)
{
p->value+=2;
printf("plus 2: %d by %d\n", p->value, getpid());
}else
{
// p->value-=2;
// printf("minus 2: %d by %d\n", p->value, getpid());
sem_post( &(p->mutex));
break;
}
sem_post( &(p->mutex));
}
}
// shmdt(p);
shmctl(id, IPC_RMID, NULL);
}