0

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!

1 Answers1

0

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • thanks for your quick reply! the code works fine if i use `waitpid(pid, &status, 0)`. i'm not sure why i can use `waitpid(pid)` without `fopen()` though. – user1322538 Oct 20 '14 at 23:24
  • @user1322538: Are you writing 1972-style C? That isn't type checked, so it's *your* responsibility to read the manuals and figure out your system APIs. – Kerrek SB Oct 20 '14 at 23:29
  • that was my bad, i thought `waitpid()` works like `wait()` and the compiler didn't give me any error or warning. – user1322538 Oct 20 '14 at 23:33
  • @user1322538: C is a terrible language to use if you're not willing to do a *lot* of leg work. – Kerrek SB Oct 20 '14 at 23:35