神奇的linux:父子进程管道通讯
2013-12-11 23:16
253 查看
poll函数用于父子进程之间的管道通讯。
用法可以man一下。这里提供一个可以运行的示例。
程序流程:
父进程启动并创建子进程
子进程通过管道发送数据给父进程
父进程同时监听管道数据和shell输入,阻塞500毫秒发现没有数据就打印一个"Testing...."
父进程等待子进程结束
子进程结束,父进程结束
Ubuntu10.04:
poll.cpp源代码:
Makefile:
然后进行编译:
运行结果如下:
用法可以man一下。这里提供一个可以运行的示例。
程序流程:
父进程启动并创建子进程
子进程通过管道发送数据给父进程
父进程同时监听管道数据和shell输入,阻塞500毫秒发现没有数据就打印一个"Testing...."
父进程等待子进程结束
子进程结束,父进程结束
Ubuntu10.04:
poll.cpp源代码:
#include <stdio.h> #include <unistd.h> #include <sys/wait.h>// waitpid #include <sys/types.h>// waitpid #include <string.h>// strlen #include <poll.h>// poll /* comment: pipe is used between two processes on the same computer. */ #define TIMES 50 int main(){ int pipefds[2]; if( -1 == pipe( pipefds)){ printf( "Error when create pipes\n"); }else{ int i; pid_t pid = fork(); if( 0 == pid){// child printf( "child running\n"); close( pipefds[0]); for( i = 0; i < TIMES; ++ i){ write( pipefds[1], "iamagoodguy", strlen( "iamagoodguy")); sleep( 1); } }else{ printf( "parent running\n"); char buf[256]; close( pipefds[1]); struct pollfd pf[2];// key structure pf[0].fd = 0;// console input pf[0].events = POLLIN;// wait for bytes input pf[1].fd = pipefds[0];// pipe input pf[1].events = POLLIN;// wait for bytes input for( i = 0; i < TIMES; ++ i){ poll( pf, 2, 500);// wait for only 500 ms printf( "Testing...\n"); if( pf[1].revents & POLLIN){ buf[ read( pipefds[0], buf, 256)] = '\0'; printf( "Receive:%s\n", buf); } if( pf[0].revents & POLLIN){ buf[ read( 0, buf, 256)] = '\0'; printf( "Print:%s\n", buf); } } int status; wait( & status); } } return 0; }
Makefile:
COMPILE = g++ $< -o $@ poll: poll.cpp $(COMPILE)
然后进行编译:
make poll ./poll
运行结果如下:
相关文章推荐
- fork、execl , waitpid实现父子进程管道间通讯
- Linux下用fork()派生的子进程通过pipe管道通讯的实例详解("生产者-消费者"问题)
- Linux进程通讯:管道通讯、信号通讯、共享内存
- Linux父子进程通信--管道及FIFO通信
- linux下父子进程间的通信——管道
- 【Linux】利用管道在进程通讯拷贝文件
- linux进程通信之使用匿名管道进行父子进程通信
- Linux 进程间通讯之有名管道方式
- Linux进程间通讯方式之管道pipe
- Linux进程间通讯--管道(有名管道
- linux进程间通讯-命名管道
- Linux 进程间通讯之创建无名管道和读写无名管道
- linux_c开发(5-2)进程间通讯_管道通讯
- linux 下父子进程通过管道传输数据
- Linux 进程间通讯之创建无名管道和读写无名管道
- Linux 进程间通讯之有名管道方式
- Linux中进程通讯--无名管道
- linux进程间通讯--管道
- Linux下进程的创建及其使用管道进行进程之间的通讯[00原创]
- linux进程间通讯-匿名管道