LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 880|回复: 5

一个最简单的管道程序,为什么会有不同的输出?

[复制链接]
发表于 2003-9-29 21:46:30 | 显示全部楼层 |阅读模式
REDHAT 8.0
gcc
在学习PIPE的过程中,将以下代码编译,a.out
在终端下执行
$ a.out
输出:
hello world in parent and write to child

end read 42 bytes!


$ a.out &
输出:
begin to write 42 bytes...
hello world in parent and write to child

end read 42 bytes!
的运行结果为什么不一样?
  1. /************************************************************************************************
  2. * Name         : s_pipe1.c
  3. * Descript        : Example14.1  in Advanced Programming in the UNIX Environment
  4. * Date        : 2003-9-29 星期一 29 九月 2003
  5. * Author        : Kicool
  6. * Key        : pipe
  7. * Function        : int pipe(int filedes[2]);
  8. *************************************************************************************************/
  9. #include <sys/types.h>
  10. #include "ourhdr.h"
  11. int main(void)
  12. {
  13.     int n, fd[2];
  14.     pid_t pid;
  15.     char line[MAXLINE];
  16.     char buf[] = "hello world in parent and write to child\n";
  17.     n = strlen(buf) +1;
  18.     if (pipe(fd) < 0)
  19.         err_sys("pipe error");
  20.     if ((pid = fork()) < 0)
  21.         err_sys("fork error");
  22.     else if (pid > 0)  {
  23.         close(fd[0]);
  24.         printf("\nbegin to write %d bytes...\n", n);
  25.         write(fd[1], buf, n);
  26.     } else {
  27.         close(fd[1]);
  28.         n = read(fd[0], line, MAXLINE);
  29.         write(STDOUT_FILENO, line, n);
  30.         printf("\nend read %d bytes!\n", n);
  31.     }
  32.     exit(0);
  33. }
复制代码
发表于 2003-9-29 22:15:29 | 显示全部楼层
一样呀,只不过输出有点乱,在else if(pid >0){...} 块的最后加一句wait(NULL); 就好一点了。
发表于 2003-9-30 12:44:17 | 显示全部楼层
else if (pid > 0)  {
        close(fd[0]);
        printf("\nbegin to write %d bytes...\n", n);
        write(fd[1], buf, n);
    } else {
        close(fd[1]);
        n = read(fd[0], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
        printf("\nend read %d bytes!\n", n);
这里两个进程同时运行
所以输出结果是不定的
取决于谁会先执行

这在程序设计上就叫竞态
也就是同时改变一个共享资源
得到的结果取决于执行的顺序
 楼主| 发表于 2003-9-30 19:05:27 | 显示全部楼层
谢谢两位老大。这里的“竞态”是不是就是“race condition”?
发表于 2003-9-30 19:23:55 | 显示全部楼层
好像类似于信号量问题。
发表于 2003-9-30 19:39:03 | 显示全部楼层
可能是啊
race condition不知道是什么意思

总之结果与执行顺序相关就是竞态
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表