I am using waitpid(2) to check and mark the status of my processes of my job control program. I am using the WUNTRACED option, to catch useful signal like SIGTSTP in a job control program.
The problem is, when CTRL-Z (SIGTSTP) my program, the PID returned by waitpid(2) is correct (>0), but when killing it with a CTRL-C (SIGINT), the PID returned is -1. How is that ? How can I mark the status of my process then ? Since it return an invalid PID and set errno to ECHILD.
#include <sys/types.h>
#include <stdbool.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
pid_t pid;
pid_t ret;
int stat_loc;
if ((!(pid = fork())))
{
execve("/bin/ls", (char *const []){"ls", "-Rl", "/", NULL}, NULL);
}
else if (pid > 0)
{
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
ret = waitpid(-1, &stat_loc, WUNTRACED);
printf("\nwaitpid returned %d\n", ret);
}
return (0);
}
EDIT: Problem solved, see the trick with SIGCHLD when you ignore it.
waitpidreturn -1 on error, doperror("waitpid")to see whywaitpidfails - Pablowaitpidfailed (hence it returned -1) because you are ignoringSIGCHILD, see Andrew's answer. Though I must confess that I didn't know the reason as why it fails. - Pablo