您的位置:首页 > 其它

poll的用法示例(程序还有bug,但只是为了示例poll的用法就不改了)

2010-04-21 10:21 399 查看
//创建PIPENUM个pipe和子进程,子进程负责写,父进程负责读
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define PIPENUM 4
int fdPipe[PIPENUM][2];
int createPipe(void)
{
int i, ret;
for (i = 0; i < PIPENUM; i++) {
ret = pipe(fdPipe[i]);
if (ret == -1)
return -1;
}
return 0;
}
int childWork(int index)
{
int i;
for (i = 0; i < PIPENUM; i++) {
if (i != index) {
close(fdPipe[i][0]);
close(fdPipe[i][1]);
} else {
close(fdPipe[i][0]);
}
}
srand(getpid());
int sleepers = 3 + rand() % 8;
sleep(sleepers);
char buf[256];
sprintf(buf, "hello, this is process %d.", getpid());
int ret = write(fdPipe[index][1], buf, strlen(buf)+1);
if (ret == -1)
return ret;
return 0;
}
int fatherWork(void)
{
int i;
for (i = 0; i < PIPENUM; i++) {
close(fdPipe[i][1]);
}
int ret = fatherActualWork();
if (ret == -1) {
printf("pollo fail/n");
return -1;
}
return 0;
}

int fatherActualWork(void)
{
int i;
int ret;
char buf[256];
struct pollfd pfd[PIPENUM];
for( i=0 ; i<PIPENUM ; i++ )
{
pfd[i].fd=fdPipe[i][0];
pfd[i].events=POLLIN;
}

while (1)
{
ret=poll(pfd, PIPENUM, -1);
if( -1==ret )
{
perror("poll");
return -1;
}
else if( 0==ret )
{
return 0;
}
for( i=0 ; i<PIPENUM ; i++ )
{
if( pfd[i].revents&POLLIN==POLLIN )
{
memset(buf, 0, 256);
read(fdPipe[i][0], buf, 256);
printf("%s/n",buf);
}
}
}
}
int main(void)
{
int ret = createPipe();
if (ret == -1)
exit(1);
int i;
pid_t pid;
for (i = 0; i < PIPENUM; i++) {
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
ret = childWork(i);
if (ret == -1) {
printf("write fail/n");
sleep(100);
exit(1);
}
exit(0);
}
}
ret = fatherWork();
if (ret == -1) {
printf("read fail/n");
exit(1);
}
exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: