I read in Advanced Programming in the Unix Environment (APUE) that a signal can interrupt wait(), causing it to return -1 and with errno==EINTR (a system interrupt). So then I started to wonder if wait() can return -1 while the child process is technically not terminated (which I'm checking with (WIFEXITED(status) || WIFSIGNALED(status))==0). I wrote out some code, which I'll paste below, which tests this. The code just forks(), attaches a signal handler to the parent and child, and then checks if wait() returns errno==EINTR. This code produce some weird results and I don't know why:
If I don't specify the
SA_RESTARTflag (the expectation is thatwait()will return and not restart), it sometimes interrupts wait and other times it doesn't. This behavior appears to be inconsistent. I'm not sure why it's happening.When
wait()correctly gets interrupted, I observeWIFEXITED(status) == 1, even though the print statement at the end of thechild_code()never shows. Meaning that it's reporting that the child exited normally, but it never actually finished its code? This seems strange.
Can anyone provide any clarification on this behavior? Here is the code:
#include
#include
#include
#include
#include
#include
#include
void child_code();
void parent_code();
void handler(int signum) {
printf("interrupted!!\n");
}
void donothing(int signum) {
}
int main(int argc, char* argv[]) {
pid_t newpid = fork();
if(newpid == -1) {
perror("fork");
exit(1);
}
else if (newpid == 0) {
// if we don't register a signal handler for the child,
// the default action for SIGINT will kill it
signal(SIGINT, donothing);
child_code();
}
else {
struct sigaction act;
sigset_t blockedset;
sigemptyset(&blockedset);
act.sa_handler = &handler;
//act.sa_flags = SA_RESTART;
act.sa_mask = blockedset;
if(sigaction(SIGINT, &act, NULL) < 0) {
perror("sigaction");
exit(1);
}
parent_code(newpid);
}
return 0;
}
void child_code() {
printf("Child %d here. Code is running...\n", getpid());
unsigned long long i;
unsigned long long j = 0;
// do something that takes forever
for (i=0; i< ULONG_MAX; i++) {
if (i%2==0)
j++;
}
printf("Child code finished: %llu\n", j);
}
void parent_code(int childpid) {
int status;
pid_t returned_pid = wait(&status);
if (returned_pid < 0) {
if (errno == EINTR) {
printf("interrupted system call!! Child exited? %d."
" Child terminated by signal? %d\n",
WIFEXITED(status), WIFSIGNALED(status));
}
perror("wait");
exit(1);
}
printf("Parent finished waiting. "
"Original pid=%d, returned pid=%d. "
"Exited? %d. Terminated by signal? %d\n",
childpid, returned_pid, WIFEXITED(status), WIFSIGNALED(status));
}