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); }
相关文章推荐
- epoll的简单用法示例(程序还有bug,但只是为了示例epoll的用法就不改了)
- 生活不仅仅只是为了房子和车子,还有诗和远方
- mmap函数用法及示例程序
- [导入]AjaxPanel自定义控件实现页面无刷新数据交互(做了个示例程序, 效果确实比较Cool, 用法非常简单! )(示例代码下载)
- AjaxPanel自定义控件实现页面无刷新数据交互(做了个示例程序, 效果确实比较Cool, 用法非常简单! )(示例代码下载)
- AjaxPanel自定义控件实现页面无刷新数据交互(做了个示例程序, 效果确实比较Cool, 用法非常简单! )(示例代码下载)
- mmap函数用法及示例程序
- Qt学习: QFileDialog和QMessageBox的用法和程序示例
- mmap函数用法及示例程序
- 新写的一个委托程序!目的为了巩固!委托的用法!
- mmap函数用法及示例程序
- 一个多线程示例程序的BUG修复
- mmap函数用法及示例程序
- 只是为了表示我还有在敲代码
- Qt学习:QLabel的用法及其程序示例
- AjaxPanel自定义控件实现页面无刷新数据交互(做了个示例程序, 效果确实比较Cool, 用法非常简单! )(示例代码下载)
- mmap函数用法及示例程序
- 微信小程序loading组件显示载入动画用法示例【附源码下载】
- Qt学习: QTabWidget多页面部件的用法及程序示例
- java程序中foreach用法示例