linuxbashkillwaitpid

kill & wait in one step


If I use a combination to kill a child process in batch and wait for it's termination, I use

kill $PID
wait $PID

If the process exists immediately, the wait will fail, since the pid is not running anymore.

Is there a way to combine both statements to a single one to aviod the error?

Edit: The process I have to kill uses a tempfile; thus it has to be closed (and not just signaled to close) to start it again. Checking the return value of kill does not help, since this indicates whether the signal was delivered successfully.


Solution

  • It's not a one-liner, but would you be willing to consider spawning off the kill with a short sleep, then waiting in the main thread? Something like:

    (sleep 1; kill $PID) &
    wait $PID
    

    This addresses your concern of the PID being reused after the kill. Even if you reduce the sleep to something much smaller, it introduces idle time, but it should at least ensure that you wait on the correct process.