Linux fork 函数

fork 函数

pid_t fork(void); fork 函数用来创建一个子进程。

fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process.

对于fork函数的返回值

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

执行成功,给父进程返回子进程ID,子进程返回 0;执行失败,-1 返回给父进程,创建子进程失败

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    pid_t pid = fork();
    if(pid == 0) {
        printf("Child: Parent Process is %d\n", getppid());
        printf("Child: Child Process is %d\n", getpid());
    }
    else if(pid > 0) {
        printf("Parent Process is %d\n", getpid());
    }
    else {
        printf("pid = %d\n", pid);
    }
    return 0;
}

执行上面程序打印如下:

Parent Process is 183
Child: Parent Process is 183
Child: Child Process is 184

fork 特点

  • 调用一次,返回两次
  • 父子进程共享正文段
  • 父子进程不共享存储空间,如:数据、堆、栈空间等。但目前内核实现不执行父进程数据段、堆、栈空间的完全复制,使用写时复制(Copy-On-Write COW)代替。
  • 写时复制:父子进程共享数据段、堆、栈,但内核将它们访问权限设为只读,当父子进程需要修改这些区域时,则内核只为修改区域的那块内存制作一个副本。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章