fork函数

    技术2022-05-11  60

    据介绍,fork函数可以作为进程的复制方法,一般情况下,fork函数的子进程和父进程共享一个代码段,而数据段、堆栈段由父进程复制到子进程,但是事实情况下为,fork函数的子进程只复制了关于该几个段的寄存器地址,只是在子进程更改数据的时候才更改父进程。(来自 Linux Programmer's Guide) 一个非常有趣的是if和esle将扮演一个非常特殊的角色,而不是我们平时所认为的单一执行的方式了。 pid_t childpid; childpid = fork(); if(-1 == childpid )  {     perror("fork");     exit(1);  }  if(0 == childpid)  //now in child process {    printf("now in child process./n");    exit(1);  // you should exit(1) in child process, so that it could release resource inherit from                 // parent process. }  else // in parent process {     printf("now in parent process./n"); } 当fork函数成功返回0时,子进程被拷贝,父进程也执行,因此会依顺序输出:        now in child process.        now in parent process. 也就是if和esle都被执行了,虽然在同一个进程中,执行的只有if或else,但是在两个进程中,同时被执行,一点特殊处,记下来,看看。 

    最新回复(0)