管道

管道是一种两个进程间进行单项通信的机制

特点如下:

  • 数据只能由一个进程流向另一个进程(其中一个读管道,一个写管道);如果要进行双工通信,则需要建立两个管道。
  • 管道只能用于父子进程或者兄弟进程间通信
    int pipe(int fd[2]);

    利用管道实现在父子进程间通信

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <cstring>
    #include <fcntl.h>
    #include <sys/stat.h>
    
    /*利用管道实现在父子进程间通信*/
    #define INPUT 0
    #define OUTPUT 1
    int main()
    {
    	int fd[2];
    	/*定义子进程号*/
    	pid_t pid;
    	char buf[256];
    	int returned_count;
    	/*创建无名管道*/
    	pipe(fd);
    	/*创建子进程*/
    	pid = fork();
    	if (pid < 0)
    	{
    		printf("Error in fork\n");
    		exit(1);
    	}
    	else if (pid == 0)/*子进程*/
    	{
    		printf("in the child process...\n");
    		/*子进程向父进程些数据,关闭管道的读端*/
    		close(fd[INPUT]);
    		write(fd[OUTPUT], "hello world", strlen("hello world"));
    		exit(0);
    	}
    	else
    	{
    		printf("in the parent process...\n");
    		/*父进程从管道读取子进程写的数据,关闭管道的写端*/
    		close(fd[OUTPUT]);
    		returned_count = read(fd[INPUT], buf, sizeof(buf));
    		printf("%d bytes of data received from child process: %s\n", returned_count, buf);
    	}
    	return 0;
    }
    /*利用管道实现在父子进程间通信*/
    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值