Today, a new question about "fork() function" is interesting. This process-level function can return values twices, which makes me wonder : HOW DID IT MAKE IT?!!! Following is the test code from internet, and should be a good example.

  1. #include <unistd.h>
  2. #include <sys/types.h>
  3.  
  4. void main()
  5. {
  6. pid_t  pid;
  7. pid = fork();
  8. if (pid < 0)
  9.     printf("error in fork");
  10. else if (pid == 0)
  11.     printf(" i am the child process, my process id is %d\n", getid())
  12. else 
  13.     printf(" i am the parent process, my process id %d\n", getid());
  14. }

执行结果:
 [root@localhost c]# ./a.out 
 i am the child process, my process id is 4286 
 i am the parent process, my process id is 4285


从这个程序执行结果可以看出,fork() 在执行的时候,是返回了两次。当fork执行时,产生子进程,子进程和父进程共享代码段,并发执行。但是二者并不共享临时数据堆栈,而是子进程保存父进程的数据堆栈副本,这点值得注意!!