14 共享内存4

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值