knolz
knolz

Reputation: 191

I can't understand sigaction() result

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

void handler(int sig)
{
  pid_t pid;
  int status;

  while( (pid = waitpid(-1, &status, WNOHANG)) > 0 )
    printf("%d\n", pid);
}

int main(void)
{
  struct sigaction act;

  pid_t pid;
  int ch;

  act.sa_handler = handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  sigaction(SIGCHLD, &act, 0);

  pid = fork();
  if( pid == 0 ) {
    exit(0);
  }
  else {
    if( (ch = fgetc(stdin)) == EOF )
      printf("EOF\n");
  }
}

Hello, I want to know about sigaction function. If I execute this program, the result is like below.

[process id]
EOF

Why EOF is in stdin buffer after processing SIGCHLD signal ? I don't know why this happen. or Maybe I don't know how to use sigaction function ?

Upvotes: 1

Views: 96

Answers (1)

Barmar
Barmar

Reputation: 781626

fgetc() returns EOF if the file is at end-of-file or an error occurs while trying to read the character. In this case, read() being interrupted by a signal is an error, and the SA_RESTART option to sigaction() prevents this error.

To distinguish between EOF and error, use feof() or ferror(), or test the variable errno. errno will be 0 for the EOF case, non-zero for an error (EINTR in this case).

Upvotes: 1

Related Questions