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)代替。
  • 寫時複製:父子進程共享數據段、堆、棧,但內核將它們訪問權限設爲只讀,當父子進程需要修改這些區域時,則內核只爲修改區域的那塊內存製作一個副本。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章