1

I fork() a parent process to a child, the PID returned by fork() is stored in the parent's memory, then time passes and the child terminates; Now can I determine if the PID value stored in the parent's memory still refers to the same forked child, and how can I ensure that this PID doesn't refer to a different process with the same PID, which may eventually have born after the child terminated?

davide
  • 2,082
  • 3
  • 21
  • 30

2 Answers2

3

The operating system cannot reuse the child's PID until the parent has acknowledged that it knows the child has stopped executing.

The parent makes the acknowledgment using the wait and waitpid calls. The children that terminate are kept in a "zombie" state while the parent doesn't call these functions. After these calls return the parent will know that if there's a process running with the same PID that the child had, it's not the child.

For extra safety you might be interested in checking the parent PID of the child process.

Community
  • 1
  • 1
Joni
  • 108,737
  • 14
  • 143
  • 193
1

You can:

  • call man 2 wait in parent, to get notification when child dies;
  • invent your polling protocol between parent and child. If child still the same, it must respond to parent's poll with the same value as it did right after the spawn. You can use some POSIX IPC mechanism for this. This can be useful when your parent has only one execution thread and you can't use threads in parent.
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51