Inter-process synchronization methods
You want to synchronize the execution of a parent and child process on Linux, so that the parent waits for the child to do step 1, then the child waits for the parent to do step 2, and so on. How do you do it?
(Motivating example: The test program I wrote for "POSIX semaphores do not auto-release on exit")
waitpidis the simplest method, but it only lets one process wait for the other to exit.- It's natural to reach for signals: process A calls
pause, process B callskill. Exceptpausesuffers from the missed-wakeup problem, so you need to mask the signal first withsigprocmask, then unblock the process, and then callsigwait. Also, make sure to remember to usesigwaitinstead ofsigsuspend, as the former swallows terminating signals while the latter doesn't, andSIGUSR1is a terminating signal. And definitely don't try to setSIGUSR1toSIG_IGNto prevent that, becausesigsuspenddoesn't wake up for ignored signals even if they are in the signal mask you pass to it. - If you've lost your appetite for signals, then consider taking advantage of the blocking nature of reading from pipes as a simple synchronization mechanism. Process A calls
readto wait, process B callswriteto unblock. You can just write an arbitrary byte since it is the receipt of the data and not its contents that matters. What makes this slightly awkward is that bidirectional communication requires two pipes and thus four file descriptors. - A little more lightweight than pipes is
eventfd, which is very similar except that there is only one file descriptor that you can bothreadandwrite(or use the glibc wrapper functionseventfd_readandeventfd_write), and it holds a single 8-byte integer instead of a large buffer. Just remember that you have towritesomething other than 0 (unlike for pipes) because 0 is the special empty value. - A little more heavyweight than pipes is
socketpairto create an anonymous full-duplex connection with two sockets. - Of course you can use POSIX semaphores.
I find eventfd the cleanest, but (unlike pipes and socketpair) it can't detect when the other process has exited abnormally.