Search code examples
cprocessfopenwaitpid

waitpid() returns -1 if fopen() exists


i was wondering why waitpid() returns -1 while fopen() exists.

FILE *fp = fopen ("abc.txt", "r");
fclose(fp);

pid_t pid = fork ();
if (pid == 0) { /* child process */
    printf ("child %d\n", getpid());
}
else {                  /* parent process */
    pid_t pid2 = waitpid (pid);
    printf ("parent %d\n", pid2);
}

pid2 equals to -1 from the above example, but it becomes the same number as pid (child process number) if i eliminate fopen(). thanks for clarifying!


Solution

  • You're ignoring the error, so it's impossible to tell.

    My best guess is that your waitpid call is interrupted by the CHLD signal from the dead child.

    Test the error code to make sure:

    int status;
    pid_t pid2;
    while ((p = waitpid(pid, &status, 0)) == -1)
    {
        printf("waitpid error: %s\n", strerror(errno));
    }
    printf("reaped child: %d\n", pid2);
    

    If you don't care about SIGCHLD, block the signal before doing the forking.