#Linux系统编程(进程通信之管道通信)

(一)发行版:Ubuntu16.04.7


(二)记录:

(1)管道通信分类:

有名管道,无名管道。

(2)无名管道:

只可用于有关系的进程,比如父子进程。

 (3)pipe函数:

头文件:<unistd.h>

函数原型:int pipe(int pipefd[2]);

作用:创建管道

pipefd[0]读端

pipefd[1]写端

管道创建需要在创建进程之前。保证父子进程是在同一个管道。

(4)创建无名管道编译运行:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(void)
{
 pid_t pid;
 int fd[2];
 //创建管道
 pipe(fd);
 printf("fd[0] is %d\n",fd[0]);
 printf("fd[1] is %d\n",fd[1]);
 pid=fork();
 if(pid<0)
 	printf("error.\n");
 //父进程
 if(pid>0){


 }
 //子进程
 if(pid==0){


 }

}

之所以是3和4是因为,0、1、2是标准输入、输出、出错

fd[0]读,fd[1]写

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

int main(void)
{
 pid_t pid;
 int fd[2];
 char buf[32]={0};
 //创建管道
 pipe(fd);
 printf("fd[0] is %d\n",fd[0]);
 printf("fd[1] is %d\n",fd[1]);
 pid=fork();
 if(pid<0)
 	printf("error.\n");
 //父进程
 if(pid>0){
 	int status;
	close(fd[0]);
	write(fd[1],"hello",5);
    close(fd[1]);
	wait(&status);
    exit(0);
 }
 //子进程
 if(pid==0){
 	close(fd[1]);
    read(fd[0],buf,32);
    printf("buf is %s\n",buf);
	close(fd[0]);
	exit(0);
 }

}

 (5)有名管道:

可以做到两个没有关系的进程之间的通信。通过创建一个fifo文件,不需要在进程创建前创建有名管道,这是与无名管道不同的。

(6)mkfifo函数:

(7)命令创建有名管道:

 

可以发现管道是不占空间的

(8)mkfifo函数创建有名管道:

ymgd_write.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char *argv[])
{

 int ret;
 int fd;

 if(argc<2){
    printf("Usage:%s<fifo name>\n",argv[0]);
	return -1;
 }

//access判断管道文件是否存在,不存在则创建
if(access(argv[1],F_OK)==-1){
 ret =mkfifo(argv[1],0666);
 if(ret == -1)
 	{
   printf("mkfifo is error\n");
   return -2;
 }
 printf("mkfifo is ok\n");
}

fd =open(argv[1],O_WRONLY);
while(1){
   sleep(1);
   write(fd,"hello",5);
}

close(fd);

return 0;


 }



ymgd_read.c 

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc,char *argv[])
{
 int ret;
 int fd;
 char buf[32]={0};

if(argc<2){
   printf("Usage:%s<fifo name>\n",argv[0]);
   return -1;
}

fd =open(argv[1],O_RDONLY);
while(1){
   sleep(1);
   read(fd,buf,32);
   printf("buf is %s\n",buf);
   memset(buf,0,sizeof(buf));
}

close(fd);

return 0;

 }




运行效果 

通信是通过fifo这个文件进行的,实现没有亲缘关系的通信。 


(三)命令:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值