Linux C系统编程-进程之间的通信管道(四)

进程之间的通信

无名管道

无名管道其实是一个数组来的,里面存放着读端与写端的文件描述符。作用范围有亲缘关系的两个进程。

初始化无名管道
man 2 pipe
在这里插入图片描述
pipefd: 具有两个int类型成员的数组的首元素地址。

返回值:
成功:0
失败:-1

int fd[2];
pipe(fd); 结果: fd[0]->读端 fd[1]->写端

实现使用无名管道,使得父子进程之间通信。

int main()
{
	int ret;
	pid_t x;
	int fd[2] = {0};  //fd[0] = 0  fd[1] = 0
	ret = pipe(fd);  
	if(ret != 0)
	{
		printf("pipe error!\n");
	}
	
	printf("fd[0] = %d\n",fd[0]);
	printf("fd[1] = %d\n",fd[1]);
	
	x = fork();
	if(x > 0)
	{
		char buf[10];
		read(fd[0],buf,sizeof(buf));
		printf("buf:%s\n",buf);
		
		wait(NULL);
		exit(0);
	}
	
	if(x == 0)
	{
		char buf[10] = "hello";
		write(fd[1],buf,strlen(buf));
		exit(0);
	}

	return 0;
}

有名管道

有名管道是一个文件,作用范围是整个系统中任意的两个进程!

mkfifo()
man 3 mkfifo
在这里插入图片描述
功能:make a FIFO special file 管道文件是一种特殊的文件,不同于普通文件。

pathname:需要创建的管道文件的路径
mode:八进制权限
返回值:
成功:0
失败:-1

实现1.c文件发送数据给2.c。
1.c ->读端

int main()
{
	umask(0000);
	
	int ret = mkfifo("/home/gec/test_fifo",0777);
	if(ret == -1)
	{
		printf("mkfifo error!\n");
	}
	
	int fd = open("/home/gec/test_fifo",O_RDWR);
	if(fd < 0)
	{
		printf("open error!\n");
	}
	
	char buf[100] = {0};
	read(fd,buf,sizeof(buf));
	printf("from fifo:%s",buf);
	
	close(fd);
	
	return 0;
}

2.c写端

int main()
{
	int fd = open("/home/gec/test_fifo",O_RDWR);
	if(fd < 0)
	{
		printf("open error!\n");
	}
	
	char buf[50] = {0};
	fgets(buf,50,stdin); //最多从键盘中获取50个字节  -> 包含\n在内
	write(fd,buf,strlen(buf));
	close(fd);
	return 0;
}

无论哪个程序先运行都可以,创建之前判断管道是否存在。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值