在這裡,我們將看到在C語言中fork()和exec()系統呼叫的效果。 fork用於透過複製呼叫程序來建立一個新的進程。新進程是子進程。請參考以下屬性。
fork()傳回子程序的PID。如果值非零,則為父進程的ID,如果值為0,則為子進程的ID。
exec()系統呼叫用於用新的進程映像取代目前進程映像。它將程式載入到當前空間,並從入口點運行。
因此,fork()和exec()之間的主要差異在於fork()啟動了一個與主行程相同的新行程副本。 exec()用新的進程映像取代目前進程映像,父進程和子進程同時執行。
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> int main() { pid_t process_id; int return_val = 1; int state; process_id = fork(); if (process_id == -1) { //when process id is negative, there is an error, unable to fork printf("can't fork, error occured</p><p>"); exit(EXIT_FAILURE); } else if (process_id == 0) { //the child process is created printf("The child process is (%u)</p><p>",getpid()); char * argv_list[] = {"ls","-lart","/home",NULL}; execv("ls",argv_list); // the execv() only return if error occured. exit(0); } else { //for the parent process printf("The parent process is (%u)</p><p>",getppid()); if (waitpid(process_id, &state, 0) > 0) { //wait untill the process change its state if (WIFEXITED(state) && !WEXITSTATUS(state)) printf("program is executed successfully</p><p>"); else if (WIFEXITED(state) && WEXITSTATUS(state)) { if (WEXITSTATUS(state) == 127) { printf("Execution failed</p><p>"); } else printf("program terminated with non-zero status</p><p>"); } else printf("program didn't terminate normally</p><p>"); } else { printf("waitpid() function failed</p><p>"); } exit(0); } return 0; }
The parent process is (8627) The child process is (8756) program is executed successfully
以上是在C語言中,fork()和exec()的差異是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!