神奇的linux:父子进程管道通讯

poll函数用于父子进程之间的管道通讯。

用法可以man一下。这里提供一个可以运行的示例。

程序流程:

  1. 父进程启动并创建子进程
  2. 子进程通过管道发送数据给父进程
  3. 父进程同时监听管道数据和shell输入,阻塞500毫秒发现没有数据就打印一个"Testing...."
  4. 父进程等待子进程结束
  5. 子进程结束,父进程结束


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

运行结果如下:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值