fork function

/* 包含头文件*/
#include <unistd.h>

fork(), 用于创建子进程。如果成功,创建一个新进程并返回新进程的进程ID(给父进程)和0(�o子进程),如果不成功,则返回-1给父进程。
示例:
  pid_t pid = fork();
其中pid_t实际上为int类型。成功执行后,在父进程中,pid为所创建的子进程号;在子进程中,则为0。

创建出来的子进程和父进程几乎一样。意思是说,子进程的变量、栈、堆以及将要执行的代码段都是一样,但执行结果、时间就不能确定。以下为一个例子,可以反映一些问题。具体看注释。(本程序在Linux, gcc下编译通过,注释若有语法错误请见谅)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
   /* Fork, will create an child process, which copy the context
    * from its father process. That means the variables, the stack
    * and the heap are all as the same.
    * */
   int *p = ( int *)malloc( sizeof( int));
  *p = 1;
  pid_t pid = fork();
   if (pid == 0) {
    *p = 2;
  }
   /* you can change "pid > 0" to "pid == 0",
    * but you can find that the two value of '*p'
    * that printed are always unequal.
    * */
   if (pid > 0) {
     /* if on windows, system("pause") will be used instead */
    system( "sleep 3;");  
  }
  printf( "*p = %d, paddr = %p\n", *p, p);
   /* this will not cause error because the
    * address that p points to are not in the
    * same heap, though the value of p are equal
    * */
  free(p);
  
   return 0;
}


你可能感兴趣的:(fork)