歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux中使用poll函數

Linux中使用poll函數

日期:2017/3/1 9:47:46   编辑: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(只有poll部分是這個程序使用的):

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

然後進行編譯:

make poll
./poll

運行結果如下:

Copyright © Linux教程網 All Rights Reserved