各位看官好,上回講了fork()創建進程,今天深入剖析父進程與子進程的關係。
進程A運行中創建進程B → A是父進程,B是子進程。程序世界屬「父系社會」,無「母進程」之說(笑)。
#include
#include
int main() {
pid_t pid = fork();
sleep(5);
if (pid > 0) {
printf("PID: %d -> Father Process is running\n", getpid());
} else if (pid == 0) {
printf("PID: %d -> Son Process is running\n", getpid());
} else {
printf("Create process failed\n");
return 1;
}
return 0;
}
$ ./s
PID: 3212 -> Father Process is running
PID: 3213 -> Son Process is running
雖然父子進程共享代碼段、數據段,執行相同的main函數,但fork()在父子進程中返回值不同:
fork()返回子進程PID(>0) → 執行if(pid>0)分支fork()返回0 → 執行else if(pid==0)分支這就是同一代碼、不同輸出的核心原因!
ps x確認確有兩個./s進程運行(PID 3212、3213),程序邏輯完全正確。
fork()一次調用、兩次返回完整代碼在資源區。下回我們將講解進程互斥,敬請期待!