1. 使用共享内存进行亲缘关系的进程间通信,当使用IPC_PRIVATE实现时,fork函数一定要在shmget函数之后。
父子进程要分别进行内存映射。
2. 实例
a. 父进程完成内存映射后,等待读取用户输入信息;当输入完成后,通过kill向子进程发送SIGUSR1信号告知有消息可读,同时父进程进入睡眠状态;
b. 子进程完成内存映射后,就进入休眠状态;当收到信号后,进程唤醒,并从共享内存中读取信息;读取完成后向父进程发送SIGUSR2信号,告知,信息被读取,你可以继续输入了。
#include "sys/shm.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
void myfun(int signum)
{
return ;
}
int main()
{
int shmid;
int key;
char *p;
int pid;
shmid=shmget(IPC_PRIVATE,128,IPC_CREAT | 0777);
if(shmid <0)
{
printf("creat share memory failure\n");
return -1;
}
printf("creat share memory sucess shmid=%d\n",shmid);
pid=fork();
if(pid > 0)//parent process
{
signal(SIGUSR2,myfun);
p=(char *)shmat(shmid,NULL,0);
if(p == NULL)
{
printf("parent process:shmat function failure\n");
return -3;
}
while(1)
{
//write share memory
printf("parent process start write share memory:\n");
fgets(p,128,stdin);
kill(pid,SIGUSR1);// child process read data
pause();// wait child process read
}
}
if(pid == 0)//child process
{
signal(SIGUSR1,myfun);
p=(char *)shmat(shmid,NULL,0);
if(p == NULL)
{
printf("child process shmat function failure\n");
return -3;
}
while(1)
{
pause();// wait parent process write
//start read share memory
printf("share memory data:%s",p);
kill(getppid(),SIGUSR2);
}
}
shmdt(p);
shmctl(shmid,IPC_RMID,NULL);
system("ipcs -m ");
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/fourteen$ gcc shmctl.c
alex@alex-virtual-machine:/extra/process/fourteen$ ./a.out
creat share memory sucess shmid=2228235
parent process start write share memory:
hello
share memory data:hello
parent process start write share memory:
hello
share memory data:hello
parent process start write share memory:
what
share memory data:what