聲明:如需引用或者摘抄本博文源碼或者其文章的,請在顯著處注明,來源於本博文/作者,以示尊重勞動成果,助力開源精神。也歡迎大家一起探討,交流,以共同進步~ 0.0
多進程代碼框架示例
/* @url:http://www.cnblogs.com/johnnyzen/p/8022597.html @author:Johnny Zen @school:XiHua University @contact:johnnyztsd@gmail.com or 1125418540@qq.com @date:2017-12-11 13:08 @description:Linux下多進程代碼框架[C編程] @environment:Linux For Ubuntu 16.04/64 */ #include<sys/types.h> #include<signal.h> int main(){ pid_t sub_a, sub_b, sub_c, sub_d;//4個子進程 while((sub_a = fork()) == -1);//在主進程下,創建子進程a if(sub_a > 0){//在主進程中,且成功創建子進程a while((sub_b = fork()) == -1); //在主進程下,創建子進程b if(sub_b > 0){//在主進程中,且成功創建子進程b while((sub_c = fork()) == -1); //在主進程下,創建子進程c if(sub_c > 0){//在主進程中,且成功創建子進程c while((sub_d = fork()) == -1); //在主進程下,創建子進程d if(sub_d > 0){//在主進程中,且成功創建子進程d printf("在主進程中,且已成功創建子進程a/b/c/d:[Current PID:%d; Parent PID:%d;sub_a pid:%d;sub_b pid:%d;sub_c pid:%d;sub_d pid:%d;]\n", getpid(), getppid(), sub_a, sub_b, sub_c, sub_d); } else {//在子進程d中 printf("在子進程d中:[Current PID:%d; Parent PID:%d;sub_d pid:%d]\n", getpid(), getppid(), sub_d); } } else {//在子進程c中 printf("在子進程c中:[Current PID:%d; Parent PID:%d;sub_c pid:%d]\n", getpid(), getppid(), sub_c); } } else {//在子進程b中 printf("在子進程b中:[Current PID:%d; Parent PID:%d;sub_b pid:%d]\n", getpid(), getppid(), sub_b); } } else { //在子進程a中 printf("在子進程a中:[Current PID:%d; Parent PID:%d;sub_a pid:%d]\n", getpid(), getppid(), sub_a); } return 0; } /* 運行結果: 在子進程a中:[Current PID:4605; Parent PID:4604;sub_a pid:0] 在子進程b中:[Current PID:4606; Parent PID:4604;sub_b pid:0] 在主進程中,且已成功創建子進程a/b/c/d:[Current PID:4604; Parent PID:4189;sub_a pid:4605;sub_b pid:4606;sub_c pid:4607;sub_d pid:4608;] 在子進程c中:[Current PID:4607; Parent PID:4604;sub_c pid:0] 在子進程d中:[Current PID:4608; Parent PID:1520;sub_d pid:0] */
運行效果
另附一份自己的進程相關實驗源碼
方便道友們學習之用
#include <stdio.h> #include <signal.h> #include <unistd.h> void waiting(),stop(),alarming(); int wait_mark; void main() { int p1,p2;//聲明兩個子進程變量 if(p1=fork())//創建子進程1 { if(p2=fork())//創建子進程2 { wait_mark=1;//等待標記 signal(SIGINT,stop);//捕捉中斷信號,執行stop signal(SIGALRM,alarming);//捕捉SIGALRM信號,執行alarming waiting();//等待軟中斷信號,5s內按【DEL】發送中斷信號SIGINT,否則會向當前進行發送SIGALRM信號。 kill(p1,16);//向子程序p1發送信號16 kill(p2,17);//向子程序p2發送信號17 wait(0);//等待第一個子進程終止 wait(0);//等待第二個子進程終止 printf("parent process is killed!\n");//輸出父進程終止 exit(0);//正常終止父進程 } else { wait_mark=1;//等待標記 signal(17,stop);//子進程p2接收到信號后執行stop signal( SIGINT,SIG_IGN);//忽略中斷信號SIGINT對本進程的影響 while(wait_mark!=0); lockf(1,1,0);//鎖定屏幕,不讓其他進程輸出 printf("children process2 is killed by parent\n");//輸出進程2被父進程終止 lockf(1,0,0);//解鎖 exit(0);//正常終止進程2 } } else { wait_mark=1;//等待標記 signal(16,stop);//子進程p2接收到信號后執行stop signal(SIGINT,SIG_IGN);//忽略中斷信號SIGINT對本進程的影響 while(wait_mark!=0) lockf(1,1,0);//鎖定屏幕,不讓其他進程輸出 printf("children process1 is killed by parent\n");//輸出進程1被父進程終止 lockf(1,0,0);//解鎖 exit(0);//正常終止進程1 } } void waiting() { sleep(5);//等待5S if(wait_mark!=0) kill(getpid(),SIGALRM);//對當前進程發送SIFALRM信號 } void alarming() { wait_mark=0; } void stop() { wait_mark=0; }
參考文獻
原創。