http://blog./uid-27164517-id-3307949.html 2012 一個關(guān)于fork的思考
- #include<stdio.h>
- #include<sys/types.h>
- #include<unistd.h>
- int i=5;
- int main()
- {
- int j;
- pid_t pid;
- //pid = fork();//子進(jìn)程是從fork后的語句開始執(zhí)行的,所以這樣起不到創(chuàng)建兩個子進(jìn)程的效果
- for(j=0; j<2; j++)
- {
- //pid = fork();//請思考為什么fork不能放在循環(huán)里,
- pid = vfork();//請比較此例中創(chuàng)建兩個子進(jìn)程和下例中用遞歸創(chuàng)建有什么不同
- switch(pid)
- {
- case 0:
- i++;
- printf("CP is run\n");
- printf("%d\n%d\n",i,getpid());
- break;
- case -1:
- perror("pc failed");
- break;
- default:
- printf("PP is run\n");
- printf("%d\n%d\n",i,getpid());
- break;
- }
- }
- exit(0);
- }
遞歸,可創(chuàng)建多個子進(jìn)程
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
-
- pid_t pid;
-
- /*
- * num:當(dāng)前已經(jīng)創(chuàng)建的子進(jìn)程數(shù)
- * max:需要創(chuàng)建的子進(jìn)程數(shù)
- */
- void createsubprocess(int num,int max)
- {
- if(num>=max)return;
- pid=fork();
- if(pid<0)
- {
- perror("fork error!\n");
- exit(1);
- }
- //子進(jìn)程
- else if(pid==0)
- {
- sleep(3);
- printf("子進(jìn)程id=%d,父進(jìn)程id=%d\n",getpid(),getppid());
- }
- //父進(jìn)程
- else
- {
- num++;
- if(num==1)printf("父進(jìn)程id=%d\n",getpid());
- if(num<max)createsubprocess(num,max);
- //此處加sleep是為了防止父進(jìn)程先退出,從而產(chǎn)生異常
- sleep(5);
- }
- }
-
- int main()
- {
- int num=0;
- int max=3;
- createsubprocess(num,max);
- return 0;
- }
創(chuàng)建守護(hù)進(jìn)程(遞歸)
- #include<stdio.h>
- #include<sys/types.h>
- #include<unistd.h>
- #include<signal.h>
- #include<sys/param.h>
- #include<sys/stat.h>
- #include<time.h>
- #include<syslog.h>
- int init_daemon(void)
- {
- int pid;
- int i;
- signal(SIGTTOU,SIG_IGN);
- signal(SIGTTIN,SIG_IGN);
- signal(SIGTSTP,SIG_IGN);
- signal(SIGHUP,SIG_IGN);
- //兩次創(chuàng)建子進(jìn)程,使得進(jìn)程不再是會話組長從而脫離控制終端
- pid = fork();
- if(pid>0)
- {
- exit(0);
- }
- else if(pid<0)
- {
- return -1;
- }
- setsid();
- pid = fork;
- if(pid>0)
- {
- exit(0);
- }
- else if(pid<0)
- {
- return -1;
- }
- //關(guān)閉0到最高文件進(jìn)程描述符值
- for(i=0; i<NOFILE; close(i++));
- chdir("/");
-
- umask(0);
- signal(SIGCHLD,SIG_IGN);
- return 0;
- }
- int main()
- {
- time_t now;
- init_daemon();
- syslog(LOG_USER | LOG_INFO,"測試守護(hù)進(jìn)程!\n");
- while(1)
- {
- sleep(8);
- time(&now);
- syslog(LOG_USER | LOG_INFO,"系統(tǒng)時間:\t%s\t\t\n",ctime(&now));
- }
- }
創(chuàng)建進(jìn)程扇/進(jìn)程鏈:
進(jìn)程扇:/* 由一個進(jìn)程派生多個子進(jìn)程 */ 進(jìn)程鏈:/* 由父進(jìn)程派生子進(jìn)程,子進(jìn)程再派生子進(jìn)程 */
請思考3個問題: 1.怎樣保證父子進(jìn)程的執(zhí)行順序 2.sleep的作用到底是什么? 3.break能不能換成return(0)?它們之間有什么區(qū)別?
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- int main(void)
- {
- int i;
- pid_t pid;
- printf("This is a example\n");
- for (i=0 ;i<3; i++)
- {
- if (!(pid = fork()) //創(chuàng)建進(jìn)程扇(讓子進(jìn)程跳出)
- // if ( pid = fork()) //創(chuàng)建進(jìn)程鏈(讓父進(jìn)程跳出,子進(jìn)程作為后繼的父進(jìn)程)
- break;
- }
- printf ("("My parent pid is %ld,My pid is %ld\n",getpid(),getppid());
- sleep(3);//等待所有的進(jìn)程執(zhí)行完畢
- return 0;
- }
|