管道pipe与dup结合使用,应用实例
2017-04-14 15:53
429 查看
管道的一种常见用法:在父进程创建子进程后向子进程传递参数。例如,一个应用软件有一个主进程和很多个不同子进程。
主进程创建子进程后,在子进程调用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程序:
myprocess程序:
main程序的执行结果:
myprocess begin
recv message:from parent's message
child exited with code:33
------------------------------------------------------------------------
可见,exec调用的程序获取到了主进程写入管道的数据。
这在实际项目中是经常用到的,主进程启动多个不同功能的exec调用,并通过管道的方式传递数据给启动的程序。
主进程创建子进程后,在子进程调用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[2]; pipe(fd); pid = fork(); if(0 == pid)//child read { close(fd[1]); dup2(fd[0], STDIN_FILENO); execve("myprocess", argv, environ); } else//parent write { close(fd[0]); int old = dup(STDOUT_FILENO); int new = dup2(fd[1], STDOUT_FILENO); write(fd[1], str, strlen(str)+1); dup2(old, new);//恢复重定向 wait(&stat);// if ( WIFEXITED(stat) ) { printf("child exited with code:%d\n", WEXITSTATUS(stat)); } close(fd[1]); exit(0); } }
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[30]; bzero(buf, sizeof(buf)); read(STDIN_FILENO, buf, sizeof(buf)); printf("recv message:%s\n", buf); exit(33); }
main程序的执行结果:
myprocess begin
recv message:from parent's message
child exited with code:33
------------------------------------------------------------------------
可见,exec调用的程序获取到了主进程写入管道的数据。
这在实际项目中是经常用到的,主进程启动多个不同功能的exec调用,并通过管道的方式传递数据给启动的程序。
相关文章推荐
- 管道pipe与dup结合使用
- 传统的进程间通信方式 1.无名管道(pipe) 2.有名管道(fifo) 3.信号(signal); 闹钟信号应用实例
- Python multiprocessing模块中的Pipe管道使用实例
- 《Lua程序设计》9.2 管道(pipe)与过滤器(filter) 包含使用协同函数实现“生产者——消费者”问题的实例代码
- 无名管道(pipe)使用实例
- CountDownLatch与AIDL获取应用软件大小结合使用实例
- 【编撰】linux IPC 002 - 匿名管道PIPE和有名管道FIFO的概念和实例,以及应用比较
- 实例——Linux管道pipe的使用
- Linux管道pipe使用实例
- 13-(1-4)进程管道关于popen(-r-w)及pipe的程序使用实例
- AJAX技术与asp.net 2.0的完美结合之Timer的web应用 及使用AJAX控件时的“Sys 未定义”错误解决办法
- Servlet程序应用和实例之使用Cookie简析
- 使用Delphi调用WebServices接口的简单应用实例
- C#使用XmlDocument操作XML进行查询、增加、修改、删除、保存应用的实例(转载)
- Servlet程序应用和实例之使用Cookie简析
- linux进程通信--管道(pipe)(含实例代码)
- C#中使用反射机制得到类型实例应用Demo
- [阅读报告]揭示XProc——使用管道技术支持XML应用环境
- 使用pipe()与fork()函数通过管道实现父子进程之间的通信
- 使用类前置声明的好处-结合Qt 4一个主窗口实例讲解