views:

743

answers:

4

For child processes, the wait() and waitpid() functions can be used to suspends execution of the current process until a child has exited. But this function can not be used for non-child processes.

Is there another function, which can wait for exit of any process ?

+9  A: 

Nothing equivalent to wait(). The usual practice is to poll using kill(pid, 0) and looking for return value -1 and errno of ESRCH to indicate that the process is gone.

chaos
Is it ok to have such busy-loop ?
CsTamas
Well, you don't want to make it too busy; you should `usleep()` for a while after each `kill()` that doesn't find the process gone. Then you have to strike a balance between how busy your polling is and how long it's okay for the process to be gone before you notice.
chaos
Oh, `usleep()` became obsolete while I wasn't looking, apparently. Seems you should now `nanosleep()` instead.
chaos
@chaos: maybe you wanted to write kill(pid,0)It's int kill(pid_t pid, int sig)
Metiu
@Metiu: Yeah, thanks. The inverted argument order in Perl and shell is always getting me.
chaos
+2  A: 

None I am aware of. Apart from the solution from chaos, you can use semaphores if you can change the program you want to wait for.

The library functions are sem_open(3), sem_init(3), sem_wait(3), ...

sem_wait(3) performs a wait, so you don´t have to do busy waiting as in chaos´ solution. Of course, using semaphores makes your programs more complex and it may not be worth the trouble.

Jochen Walter
+3  A: 

You could also create a socket or a FIFO and read on them. The FIFO is especially simple: Connect the standard output of your child with the FIFO and read. The read will block until the child exits (for any reason) or until it emits some data. So you'll need a little loop to discard the unwanted text data.

If you have access to the source of the child, open the FIFO for writing when it starts and then simply forget about it. The OS will clean the open file descriptor when the child terminates and your waiting "parent" process will wake up.

Aaron Digulla
+1  A: 

Maybe it could be possible to wait for /proc/[pid] or /proc/[pid]/[something] to disappear?

There are poll() and other file event waiting functions, maybe that could help?

Talkless
Yes, it's a good idea. Unless the same process id is reused so quickly - but probably this happens rarely
CsTamas