日期:2014-05-16  浏览次数:20813 次

关于fork()和sleep()程序的疑问,请高手指点
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
static void charatatime(char*);
int main()
{
  pid_t pid;
  if((pid = fork()) < 0)
  {
  printf("error fork\n");
  }
  else if(pid == 0)
  {
  sleep(1);
  charatatime("output from the child\n");
  }
  else charatatime("output from the parent\n");
  exit(0);
}
 static void charatatime(char* str)
{
  char *ptr;
  int c;
  setbuf(stdout,NULL);
  for(ptr = str;(c = *ptr++)!=0;)
  putc(c,stdout);
}
程序运行后:
[www@localhost test]$ ./test2
output from the parent
[www@localhost test]$ output from the child

为什么不是:
[www@localhost test]$ ./test2
output from the parent
output from the child
[www@localhost test]$ 


------解决方案--------------------
首先你要明白,你看到的输出来自两个进程。
可以看看这里的讨论:
http://topic.csdn.net/u/20120307/22/d6dfa4fb-3d5e-4931-8b79-d0f107cd0ca0.html#r_77811451

明白上面一点后,再看你的程序。
主程序打印完后,直接就退出了。。。所以你会立即回到提示符下面。
但子进程还没有退出,你让它睡了一秒,所以当时它还在后台运行着。然后才打印,所以……
------解决方案--------------------
主进程退出之后,shell就准备好接受你的下一个命令了,所以他输出命令行提示符

此时,子进程依然在后台运行
------解决方案--------------------
http://baike.baidu.com/view/1952900.htm
里说的很详细,我之前也是看了里面的。父进程执行完,跳出判断,直接就退出了。子进程还在运行