Reputation: 601
in the parent process I want to start a daemon to do a long time work, so I use the double fork() to create the grandchild process to start the daemon. The question is every once in a while, the child process does not exit successfully, I am sure that the printf() before the exit(0) is called, but when I use the "ps" I can see the child process pid listed, and it never exit. Do you know why this happened, should I call _exit(0) instead of exit(0) to make the child process exit?
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;
}
Upvotes: 0
Views: 933
Reputation: 385506
Using WNOHANG
instead of 0
is surely wrong. If the parent calls waitpid
(with WNOHANG
) before the child exits, the child will remain in existence as a zombie waiting to be reaped until the parent exits too.
Upvotes: 2