进程间的通信(一)

这一章节我们主要讲进程间的通信,主要方式大概有管道、信号量、消息列队、共享内存等。
首先讲管道,管道分为有名管道、无名管道。其中有名管道是用于父进程和子进程之间的通信,太过于局限。有名管道强大一些,可用于不相关 的进程之间的通信。

无名管道

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc,char *argv)
{
	int pipe_fd[2];
	char buf[5];
	pid_t cpid;
	 if(pipe(pipe_fd)==-1)
    {
		printf("create error\r\n");
		exit(1);
	}
	  cpid=fork();
   	if(cpid==-1)
   	{
		printf("create error\r\n");
		exit(1);
	}
	if(cpid==0)
	{ 
		sleep(2);
     	close(pipe_fd[0]);
     	write(pipe_fd[1],"12345",5);
   }
   else
   {
   		sleep(3);
       close(pipe_fd[1]);
     	read(pipe_fd[0],buf,5);
     	printf("buf is %s \r\n",buf);
		
   }

}

有名管道

这里编写两个程序 进行通信
//读

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#define FIFO "/tmp/myfifo"
int main(int argc,char *argv)
{
	char buf[100];
	int fd;
	if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)
	{
		printf("printf create fail\r\n");
    }
	memset(buf,0,sizeof(buf));
    fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
    if(fd==-1)
	{
		printf("open:");
		exit(1);
	}
 while(1)
 {
  if(read(fd,buf,100)==-1)
  {

    printf("no data\r\n");
 }
else
{
	printf("buf is %s\r\n",buf);
}
 }
pause();
ulink(FIFO);
}

//写

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FIFO "/tmp/myfifo"
/* 使用带参的 main 函数是因为要用户输入要写入的内容 */
int main(int argc,char **argv)
{
int fd;
char buf_w[100];
int nwrite;
/* 打开 FIFO 管道,并设置非阻塞标志 */
432
fd=open(FIFO,O_WRONLY|O_NONBLOCK,0);
if(fd==-1)
{
if(errno==ENXIO)
printf("open error:no reading process");
}
if(argc==1)
{
printf("Plese sent something\n");
}
/* 将用户输入的数据先拷贝到 buf_w 缓冲区中 */
strcpy(buf_w,argv[1]);
/* 向管道中写入字符串 */
if((nwrite=write(fd,buf_w,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try latter.\n");
}
else
{
printf("write %s to the FIFO\n",buf_w);
}
}

进程间通信(二)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值