linux fork 多程序建立
阿新 • • 發佈:2019-01-01
1)fork函式將執行著的程式分成2個(幾乎)完全一樣的程序,每個程序都啟動一個從程式碼的同一位置開始執行的執行緒。
這兩個程序中的執行緒繼續執行,就像是兩個使用者同時啟動了該應用程式的兩個副本。
2)fork函式被呼叫一次但返回兩次。兩次返回的唯一區別是子程序中返回0值而父程序中返回子程序ID。
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <sys/wait.h> #define LOOP_NUM 5 //create process number int main() { int idx=0; pid_t childpid=0; char cmd[16]={0,}; printf("LOOP start:--> \n"); while (1) { if(idx>=LOOP_NUM) { break; } idx++; printf(" create pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx); childpid = fork(); if (childpid == 0) { // 子程序中 printf(" C runing 1 pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx); sleep(1); printf(" C runing 2 pid=%d ppid=%d idx=%d \n", getpid(), getppid(), idx); // break; } else if (childpid > 0) { // 父程序中 } else { //錯誤 printf("fork error pid=%d idx=%d \n", getpid(), idx); wait(NULL); } } //父程序中回收資源 if(childpid > 0) { //childpid is child process pid in the parent process printf("FIRST PROCESS:parent create process finished! waiting for children pid=%d childpid=%d \n", getpid(), childpid); sprintf(cmd,"ps -ef | grep %d",getpid()); system(cmd); //printf("\n\n %s \n\n", cmd); wait(NULL); printf("FIRST PROCESS: all exit & wait over pid=%d \n", getpid()); } else { printf(" <--pid=%d ppid=%d childpid=%d idx=%d will exit \n", getpid(), getppid(), childpid, idx); } //exit(0); return 0; }