在父进程中,我想启动一个守护程序来完成长时间的工作,所以我使用double fork()创建孙进程以启动守护程序。问题是每隔一段时间,子进程不会成功退出,我确信在调用exit(0)之前的printf(),但是当我使用“ ps”时,我可以看到子进程列出了pid,并且它永远不会退出。你知道为什么会这样吗,我应该打电话给_exit(0)而不是exit(0)使子进程退出?
startProcess(const char *pidfile, const char *command)
pid_t pid;
char cmd[1024];
char *head = cmd;
char *end;
char *argv[128] = {0};
int argc = 0;
if( 0 == (pid=fork()) ) { //fork a child
if( 0 > setpriority(PRIO_PROCESS, 0, 0) ) {
perror();
return;
}
pid = fork(); //fork a grandchild
if(-1 == pid){
exit(-1);
}else if(0 == pid){ //grandchild process
if (snprintf(cmd, sizeof(cmd), "%s", command) <= sizeof(cmd) - 1) {
/* change command line to argc/argv format */
do {
if (argc >= sizeof(argv)/sizeof(argv[0]) - 1)
break;
for (; (*head == ' ' || *head == '\t'); head++); //remove space or TAB in the header
if (*head == '\0')
break;
if (NULL != (end = strpbrk(head, " \t"))) {
*end = '\0';
argv[argc++] = head;
head = end + 1;
} else {
argv[argc++] = head;
break;
}
} while (1);
argv[argc] = NULL; // Maximal value of argc is ARRAY_SIZE(argv) - 1.
/* execute command to start a daemon*/
execvp(argv[0], argv);
}
//should not enter here
exit(-1);
}else{ //still in child process
printf("child process exit\n");
exit(0); //child process exit, but sometimes this call seems fail
}
}else if(-1 == pid){
return;
}else{ //parent process
int status = 0;
int rv
pid_t r_pid = waitpid(pid, &status, WNOHANG);
if (pid == r_pid) {
if (WIFEXITED(status) && (0 == WEXITSTATUS(status))) {
rv = 0;
} else {
rv = -1;
}
}
return rv;
}
使用WNOHANG
代替0
肯定是错误的。如果父母在孩子退出之前致电waitpid
(并使用WNOHANG
),则该孩子将像僵尸一样存在,等待收割,直到父母退出。