管道的一种常见用法:在父进程创建子进程后向子进程传递参数。例如,一个应用软件有一个主进程和很多个不同子进程。

主进程创建子进程后,在子进程调用exec函数执行一个新程序前,通过管道给即将执行的程序传递命令行参数,子进程根据传来

的参数进行初始化或其他操作。

大致思路:

The child can then exec() another program, which inherits the standard streams.

父进程关闭 管道读端  close( fd[0] );  调用  dup2(fd[1], STDOUT_FILENO);  将管道的写端重定向到标准输出

子进程关闭 管道写端 close( fd[1] ); 调用 dup2(fd[0], STDIN_FILENO); exec调用的进程中读取标准输入

main程序:

#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h> int main(int argc, char* argv[], char** environ)
{
char* str = "from parent's message";
int stat;
pid_t pid;
int fd[]; pipe(fd); pid = fork();
if( == pid)//child read
{
close(fd[]);
dup2(fd[], STDIN_FILENO); execve("myprocess", argv, environ); }
else//parent write
{ close(fd[]);
int old = dup(STDOUT_FILENO);
int new = dup2(fd[], STDOUT_FILENO); write(fd[], str, strlen(str)+); dup2(old, new);//恢复重定向 wait(&stat);//
if ( WIFEXITED(stat) )
{
printf("child exited with code:%d\n", WEXITSTATUS(stat));
} close(fd[]); exit(); } }

myprocess程序:

#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h> int main(int argc, char* argv[])
{
printf("myprocess begin\n");
char buf[];
bzero(buf, sizeof(buf)); read(STDIN_FILENO, buf, sizeof(buf)); printf("recv message:%s\n", buf); exit(); }

main程序的执行结果:

myprocess begin
recv message:from parent's message
child exited with code:33

------------------------------------------------------------------------

可见,exec调用的程序获取到了主进程写入管道的数据。

这在实际项目中是经常用到的,主进程启动多个不同功能的exec调用,并通过管道的方式传递数据给启动的程序。

最新文章

  1. SQLServer比较两条数据是否相同
  2. Android-monkey稳定性测试(多台设备同时进行)
  3. self&amp;super
  4. PHP注册手机获取验证码代码
  5. Mac 实用工具与问题解决
  6. c# 加密转载 备忘
  7. LeetCode_Surrounded Regions
  8. Windows窗体Winform----show()与showDialog()的区别
  9. Linux中kettle启动spoon.sh遇到的问题
  10. MVC5的控制器,使用HttpPost方式时,接收的参数为null的原因
  11. RPC远程过程调用机制底层原理
  12. parameterType 和 resultType
  13. redux中间件的原理——从懵逼到恍然大悟
  14. 具体解释Java虚拟机类载入
  15. 最近学习的 Node.js 数组_函数
  16. 浏览器兼容性汇总--CSS篇
  17. Android常用第三方支付
  18. php 实现简拼
  19. BOM&amp;DOM
  20. eclipse安装spring boot插件spring tool suite

热门文章

  1. 01: git &amp; github
  2. 20145307陈俊达《网络对抗》Exp7 网络欺诈技术防范
  3. UNIX系统的显示时间何时会到尽头
  4. SPOJ - POLYNOM Polynomial(数论乱搞)题解
  5. [Pytorch]Pytorch的tensor变量类型转换
  6. Select2下拉框总结
  7. C语言中生产随机数 rand()函数
  8. python 阶乘
  9. ubuntu 14.04 (desktop amd 64) 下载
  10. rospy 中service