linux进程无名管道通信

linux进程无名管道通信

用于父子进程的通信

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

void pipe_read(int pipes[]);
void pipe_write(int pipes[]);

int main()
{
	int pipes[2];       // 文件描述符,pipes[0] 读取, pipes[1] 写入
	pid_t pid;       // pid_t 宏定义
	int rc;

	/* 应该在创建子进程前创建管道 */

	rc = pipe(pipes);   // 创建管道, 若成功返回0, 否则返回-1
	if(rc == -1){
		perror("pipes\n");
		exit(1);
	}
	
	pid = fork();   // fork()创建新进程,成功则返回两个值,子进程返回0, 父进程返回Id
					// 否则出错返回-1
	
	switch(pid){
	case -1:          // 出错
		perror("fork\n");    
		exit(1);
		
	case 0:          // 子进程
		pipe_read(pipes);
		
	default:         // 父进程
		pipe_write(pipes);
	}
	return 0;
}

void pipe_read(int pipes[])       // 读数据
{
	int c;
	int rc;
	
	close(pipes[1]);      // 关闭写入

	/* ssize_t read(int fd,void *buf,size_t count) */

	while((rc = read(pipes[0], &c, 1)) > 0){
		putchar(c);
	}
	close(pipes[0]);
	exit(0);
}

void pipe_write(int pipes[])  // 写数据
{
	int c;
	int rc;
	
	close(pipes[0]);    // 关闭读取
	
	while((c = getchar()) > 0){
		rc = write(pipes[1], &c, 1);
		if(rc == -1){
			perror("Parent: write");
			close(pipes[1]);
			exit(1);
		}
	}
	close(pipes[1]);
	exit(0);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值