在 C 中使用 `fork()` 建立多個程序
在本節中,我們將瞭解如何在 C 中使用 `fork()` 來生成子程序。我們還在每個程序中執行一些不同的任務。因此,在我們的父程序中,我們將列印不同的值。
呼叫 `fork()` 時,它會返回一個值。如果該值大於 0,則當前在父程序中,否則在子程序中。因此,使用此方法,我們可以區分這些程序。
示例程式碼
#include <stdio.h> #include <unistd.h> int main() { int n = fork(); //subdivide process if (n > 0) { //when n is not 0, then it is parent process printf("Parent process
"; } else { //when n is 0, then it is child process printf("Child process
"); } return 0; }
輸出
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out Parent process soumyadeep@soumyadeep-VirtualBox:~$ Child process soumyadeep@soumyadeep-VirtualBox:~$
廣告