- 论坛徽章:
- 0
|
在AIX5.2上测试程序,发现popen一个程序读的时候总是报被信号打断,所以写了个程序进行测试,发现当捕获SIGCHLD信号的时候,确实有这个问题,但在HP11.11和Linux 2.6内核下没有这个问题。
怀疑是主进程执行popen()的时候进行fork(),之后popen()返回,主进程接着read(),而子进程写入标准输出,也可能管道的数据有缓存,直到子进程退出close()的时候才往里写,或者写得太快,主进程还没来得及被唤醒,而子进程一退,发上发SIGCHLD信号给主进程,而主进程还在那儿read()呢,所以read()被中断,报中断错。
- #include <stdio.h> /* printf() */
- #include <stdlib.h> /* exit() */
- #include <unistd.h> /* popen() */
- #include <errno.h> /* errno */
- #include <string.h> /* strerror() */
- static void open_read(char *pname);
- static void sig_child(int signo);
- int main(int argc, char *argv[])
- {
- int i;
- int ln;
- ln = atoi(argv[2]);
- signal(SIGCHLD, sig_child);
- for(i = 0; i < ln; i++) {
- open_read(argv[1]);
- }
- exit(EXIT_SUCCESS);
- return 0;
- }
- static void open_read(char *pname)
- {
- int i;
- char buf[BUFSIZ];
- FILE *fp;
- int r;
- if ((fp = popen(pname, "r")) == NULL) {
- perror("popen");
- exit(EXIT_FAILURE);
- }
- for(i = 0; i < BUFSIZ; i++) {
- if ((r = read(fileno(fp), buf, 1)) < 0) {
- perror("error read");
- exit(1);
- } else if (r > 0) {
- (void)fprintf(stdout, "read: %s\n", buf);
- } else {
- (void)fprintf(stdout, "read finished\n");
- break;
- }
- }
- if (pclose(fp) < 0) {
- perror("pclose");
- exit(EXIT_FAILURE);
- }
- }
- static void sig_child(int signo)
- {
- fprintf(stderr, "receiving signal child\n");
- }
复制代码
[ 本帖最后由 lanying_wzw 于 2008-5-23 18:51 编辑 ] |
|