/****fork_test.c *****/#include#include#includemain(){ pid_t pid; /*此時僅有一個進(jìn)程*/ int n=4; pid=fork(); /*此時已經(jīng)有兩個進(jìn)程在同時運行*/ if(pid<0) printf("error in fork!/n");else if(pid==0) /*返回0表示子進(jìn)程*/ { n++; printf("I am the child process, my process ID is %d,n=%d/n",getpid(),n); } else /*返回大于0表示父進(jìn)程*/ { n--; printf("I am the parent process, my process ID is %d,n=%d/n",getpid(),n); }}
語句“pid=fork()”,產(chǎn)生了兩個進(jìn)程,原來存在的父進(jìn)程,新出現(xiàn)的子進(jìn)程。
父子進(jìn)程的區(qū)別除了PID不同fork函數(shù)的返回值也不相同。在父進(jìn)程中,返回子進(jìn)程Pid,子進(jìn)程則返回0;