设为首页 加入收藏

TOP

Linux中使用poll函数
2014-11-24 01:04:15 来源: 作者: 【 】 浏览:3
Tags:Linux 使用 poll 函数

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


程序流程:


poll.cpp源代码:


#include
#include
#include // waitpid
#include // waitpid
#include // strlen
#include // 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(只有poll部分是这个程序使用的):


COMPILE = g++ $< -o $@
mapfile: mapfile.cpp
$(COMPILE)
pipe: pipe.cpp
$(COMPILE)
select: select.cpp
$(COMPILE)
poll: poll.cpp
$(COMPILE)


然后进行编译:


make poll
./poll


运行结果如下:


Linux中使用poll函数


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux中使用select函数 下一篇Linux中使用flock函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: