對fork函數理解,fork函數理解
標頭檔: #include <unistd.h>
pid_t fork (void);
1. 建立一個子進程,失敗返回-1。
2. 調用一次,返回兩次。分別在父子進程中返回子進程的PID和0。利用返回值的不同,可以分別為父子進程編寫不同的處理分支。
#include <stdio.h>#include <unistd.h>int main (void) {printf ("%u進程:我要調用fork()了...\n", getpid ());pid_t pid = fork ();if (pid == -1) {perror ("fork");return -1;}if (pid == 0) {printf ("%u進程:我是%u進程的子進程。\n", getpid (),getppid ());return 0;}printf ("%u進程:我是%u進程的父進程。\n", getpid (), pid);sleep (1);return 0;}
3. 子進程是父進程的副本,子進程獲得父進程資料區段和堆棧段(包括I/O流緩衝區)的拷貝,但子進程共用父進程的程式碼片段。
#include <stdio.h>#include <stdlib.h>#include <unistd.h>int global = 100;int main (void) {int local = 200;char* heap = (char*)malloc (256 * sizeof (char));sprintf (heap, "ABC");printf ("父進程:%d %d %s\n", global, local, heap);pid_t pid = fork ();if (pid == -1) {perror ("fork");return -1;}if (pid == 0) {global++;local++;sprintf (heap, "XYZ");printf ("子進程:%d %d %s\n", global, local, heap);free (heap);return 0;}sleep (1);printf ("父進程:%d %d %s\n", global, local, heap);free (heap);return 0;}
#include <stdio.h>#include <unistd.h>int main (void) {printf ("ABC");pid_t pid = fork ();if (pid == -1) {perror ("fork");return -1;}if (pid == 0) {printf ("XYZ\n");return 0;}sleep (1);printf ("\n");return 0;}
4. 函數調用後父子進程各自繼續運行,其先後順序不確定。某些實現可以保證子進程先被調度。
#include <stdio.h>#include <unistd.h>int main (void) {printf ("父進程:");int a, b, c;scanf ("%d%d%d", &a, &b, &c);pid_t pid = fork ();if (pid == -1) {perror ("fork");return -1;}if (pid == 0) {scanf ("%d%d%d", &a, &b, &c);printf ("子進程:%d %d %d\n", a, b, c);return 0;}sleep (1);printf ("父進程:%d %d %d\n", a, b, c);return 0;}
5. 函數調用後, 父進程的檔案描述符表(進程級)也會被複製到子進程中,二者共用同一個檔案表(核心級)。
#include <stdio.h>#include <string.h>#include <fcntl.h>#include <unistd.h>int main (void) {int fd = open ("ftab.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);if (fd == -1) {perror ("open");return -1;}const char* text = "Hello, World !";if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {perror ("write");return -1;}pid_t pid = fork ();if (pid == -1) {perror ("fork");return -1;}if (pid == 0) {if (lseek (fd, -7, SEEK_CUR) == -1) {perror ("lseek");return -1;}close (fd);return 0;}sleep (1);text = "Linux";if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {perror ("write");return -1;}close (fd);return 0;}結果:Hello ,Linux !
6. 總進程數或實際使用者ID所擁有的進程數, 超過系統限制,該函數將失敗。
7. 一個進程如果希望建立自己的副本並執行同一份代碼,或希望與另一個程式並發地運行,都可以使用該函數。
注意:fork之前的代碼只有父進程執行,fork之後的代碼父子進程都有機會執行, 受代碼邏輯的控制而進入不同分支。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。