#include<unistd.h>pid_tfork(void);/* In parent: returns process ID of child on success, or –1 on error;
in successfully created child: always returns 0*/// 常用的使用模板如下:
pid_tchildPid;/* Used in parent after successful fork()
to record PID of child */switch(childPid=fork()){case-1:/* fork() failed *//* Handle error */case0:/* Child of successful fork() comes here *//* Perform actions specific to child */default:/* Parent comes here after successful fork() *//* Perform actions specific to parent */}
#include<sys/wait.h>intwaitid(idtype_tidtype,id_tid,siginfo_t*infop,intoptions);/* Returns 0 on success or if WNOHANG was specified and
there were no children to wait for, or –1 on error */
#include<signal.h>#include<libgen.h> /* For basename() declaration */#include"tlpi_hdr.h"#define CMD_SIZE 200
#define SYNC_SIG SIGUSR1 /* Synchronization signal */staticvoid/* Signal handler - does nothing but return */handler(intsig){}intmain(intargc,char*argv[]){charcmd[CMD_SIZE];pid_tchildPid;sigset_tblockMask,origMask,emptyMask;structsigactionsa;setbuf(stdout,NULL);/* Disable buffering of stdout */sigemptyset(&blockMask);sigaddset(&blockMask,SYNC_SIG);/* Block signal */if(sigprocmask(SIG_BLOCK,&blockMask,&origMask)==-1)errExit("sigprocmask");sigemptyset(&sa.sa_mask);sa.sa_flags=SA_RESTART;sa.sa_handler=handler;if(sigaction(SYNC_SIG,&sa,NULL)==-1)errExit("sigaction");printf("Parent PID=%ld\n",(long)getpid());switch(childPid=fork()){case-1:errExit("fork");case0:/* Child: immediately exits to become zombie */printf("Child (PID=%ld) exiting!!\n",(long)getpid());sleep(3);if(kill(getppid(),SYNC_SIG)==-1)errExit("kill");_exit(EXIT_SUCCESS);default:/* Parent */sigemptyset(&emptyMask);if(sigsuspend(&emptyMask)==-1&&errno!=EINTR)errExit("sigsuspend");printf("got signal\n");if(sigprocmask(SIG_SETMASK,&origMask,NULL)==-1)errExit("sigprocmask");snprintf(cmd,CMD_SIZE,"ps | grep %s",basename(argv[0]));system(cmd);/* View zombie child *//* Now send the "sure kill" signal to the zombie */if(kill(childPid,SIGKILL)==-1)errMsg("kill");sleep(3);/* Give child a chance to react to signal */printf("After sending SIGKILL to zombie (PID=%ld):\n",(long)childPid);system(cmd);/* View zombie child again */exit(EXIT_SUCCESS);}}