LinuxSir.cn,穿越时空的Linuxsir!

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

请教有关fork的问题

[复制链接]
发表于 2006-7-31 16:07:32 | 显示全部楼层 |阅读模式
请高手帮忙解释如下程序的输出:

  1. #include        <signal.h>
  2. #include        <unistd.h>
  3. #include        "ourhdr.h"

  4. int
  5. main(void)
  6. {
  7.         pid_t   pid;
  8.         printf("%s",getlogin());
  9.         if ( (pid = fork()) < 0)
  10.                 err_sys("fork error");
  11.         else if (pid != 0) {            /* parent */
  12.                 sleep(2);
  13.                 exit(2);                                /* terminate with exit status 2 */
  14.         }
  15.         if ( (pid = fork()) < 0)
  16.                 err_sys("fork error");
  17.         else if (pid != 0) {
  18.                 sleep(4);
  19.                 abort();                                /* terminate with core dump */
  20.         }

  21.                                                                 /* second child */
  22.         if ( (pid = fork()) < 0)
  23.                 err_sys("fork error");
  24.         else if (pid != 0) {
  25.                 execl("/usr/bin/dd", "dd", "if=/boot", "of=/dev/null", NULL);
  26.                 exit(7);                                /* shouldn't get here */
  27.         }

  28.                                                                 /* third child */
  29.         if ( (pid = fork()) < 0)
  30.                 err_sys("fork error");
  31.         else if (pid != 0) {
  32.                 sleep(4);
  33.                 exit(0);                                /* normal exit */
  34.         }

  35.                                                                 /* fourth child */
  36.         sleep(6);
  37.         kill(getpid(), SIGKILL);        /* terminate with signal, no core dump */
  38.         exit(6);                                        /* shouldn't get here */
  39. }
复制代码

如果login:root, 输出为rootrootrootroot,为什么?
发表于 2006-7-31 19:10:16 | 显示全部楼层
应该是在你的父进程中的标准输出缓存里有 "root"(没输出到屏幕),结果子进程里都会有一个拷贝,在进程结束的时候缓存的数据会输出到屏幕,所以就这样了:)
回复 支持 反对

使用道具 举报

发表于 2006-7-31 19:18:46 | 显示全部楼层
贴代码要放在[ code ]...[ / code ]里面;
/* third child */  里的 sleep() 有错。。。


楼上说的有道理,应该是缓存的问题
你看的是《UNIX 环境高级编程》吧,,里面说了 exit() 与 _exit() 的分别,
你换下试
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-8-1 09:33:58 | 显示全部楼层

谢谢楼上两位,偶还有些疑惑,再请教

当把printf("%s",getlogin())改成printf("%s\n",getlogin())时,只输出一个root,
这又是为什么啊?
回复 支持 反对

使用道具 举报

发表于 2006-8-1 19:32:44 | 显示全部楼层
stdout是行缓存,碰到换行符会清空缓存……
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

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