linux下fork指令
阿新 • • 發佈:2018-11-26
linux下執行以下程式碼
-
無選項編譯連結
用法:#gcc test.c
作用:將test.c預處理、彙編、編譯並連結形成可執行檔案。這裡未指定輸出檔案,預設輸出為a.out。 -
選項 -o
用法:#gcc test.c -o test
作用:將test.c預處理、彙編、編譯並連結形成可執行檔案test。-o選項用來指定輸出檔案的檔名。#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { pid_t val; printf("PID before fork(): %d \n",(int)getpid()); val=fork(); if ( val > 0) { printf("Parent PID: %d\n",(int)getpid()); }else if (val == 0) { printf("Child PID: %d\n",(int)getpid()); }else { printf(“Fork failed!”); exit(1); } }
當val等於0時,為子程序,
當val等於1時,為父程序。
子程序和父程序都執行,父程序執行val>0後的,子程序執行val==0後的。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { pid_t val; int exit_code = 0; val=fork(); if (val > 0) { int stat_val; pid_t child_pid; child_pid = waitpid(val,&stat_val,0); printf("Child has finished: PID = %d\n", child_pid); if(WIFEXITED(stat_val)) printf("Child exited with code %d\n", WEXITSTATUS(stat_val)); else printf("Child terminated abnormally\n"); exit(exit_code); } else if (val == 0) { execlp("ls","ls","-l",NULL); //更換程式碼段 } }
待子程序執行完後父程序再執行。