Linux进程间通讯(IPC机制)——管道

十三.进程间通讯(IPC机制)——管道

1.进程间通讯方式

管道,信号量,共享内存,消息队列,套接字。

2.管道的概念

只能以只读只写管道。

管道文件:创建好内存中分配。(目的:进程间通讯)

3.有名管道

3.1 创建有名管道

命令 mkfifo 管道名

3.2 运行有名管道

创建a.c,只读文件

#include<stdlib.h> 
#include<unistd.h>
 #include<fcntl.h> 
#include<string.h> 


int main() 
{
		int fdw = open("FIFO",0_WRONLY); 
		if(fdw == -1) exit(1); 
		char buff[128] = {0}; 
		while(1) 
		{
			memset(buff,0,128); 
			printf("input:"); 
			fgets(buff,128,stdin); 
			if(strncmp(buff,"end",3) == 0) 
			{
					break; 
			}
			write(fdw,buff,strlen(buff));
		} 
		close(fdw); 


		exit(0); 
}

创建b.c 只写

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> 
#include<fcntl.h>
#include<string.h>

int main()
{
		int fdr = open("FIFO" ,O_RDONLY); 
		if(fdr == -1) exit(1);
		char buff[128] = {0};
		while(1)
		{
			memset(buff,0,128);
			int num = read(fdr,buff,128); if(num == 0) break;
			printf("read = %s\n",buff);
		}
		close(fdr);
		exit(0);
}

4.无名管道

可以用于父子进程间通信

#include<stdio.h> 
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h> 
#include<string.h> 
int main()
{
		int fd[2];
		if(pipe(fd) == -1) exit(1); 
		pid_t pid = fork();
		if(pid == -1) exit(1); 
		if(pid ==0)
		{
			close(fd[1]);
			char buff[128] = {0}; 
			read(fd[0],buff,127); 
			printf("%s\n",buff); 
			close(fd[0]);
		} 
		else{
			close(fd[0]);
			write(fd[1],"hello",5); 
			close(fd[1]);
		}
exit(0) 
}

5.管道的特点

半双工:一端只能进行一件事,只读或只写

管道没有数据,read阻塞

管道的写端关闭,read返回0

管道读端关闭,写端产生异常(发送信号,SIGPIPE,程序收到信号 异常终止)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值