Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for arbitrary process and get its exit code in Linux

Tags:

linux

shell

Is there a way to wait until a process finishes if I'm not the one who started it?

e.g. if I ran "ps -ef" and pick any PID (assuming I have rights to access process information) - is there a way I can wait until the PID completes and get its exit code?

like image 427
user1296013 Avatar asked Mar 27 '12 15:03

user1296013


2 Answers

You could use strace, which tracks signals and system calls. The following command waits until a program is done, then prints its exit code:

$ strace -e none -e exit_group -p $PID       # process calls exit(1)
Process 23541 attached - interrupt to quit
exit_group(1)                          = ?
Process 23541 detached

$ strace -e none -e exit_group -p $PID       # ^C at the keyboard
Process 22979 attached - interrupt to quit
--- SIGINT (Interrupt) @ 0 (0) ---
Process 22979 detached

$ strace -e none -e exit_group -p $PID       # kill -9 $PID
Process 22983 attached - interrupt to quit
+++ killed by SIGKILL +++

Signals from ^Z, fg and kill -USR1 get printed too. Either way, you'll need to use sed if you want to use the exit code in a shell script.

If that's too much shell code, you can use a program I hacked together in C a while back. It uses ptrace() to catch signals and exit codes of pids. (It has rough edges and may not work in all situations.)

I hope that helps!

like image 98
andrew-e Avatar answered Oct 13 '22 20:10

andrew-e


is there a way I can wait until the PID completes and get its exit code

Yes, if the process is not being ptraced by somebody else, you can PTRACE_ATTACH to it, and get notified about various events (e.g. signals received), and about its exit.

Beware, this is quite complicated to handle properly.

like image 28
Employed Russian Avatar answered Oct 13 '22 19:10

Employed Russian