Wait for an arbitrary process and get the exit code in Linux.

Is there a way to wait for the process to finish, if I'm not the one who started it?

eg. if I run "ps -ef" and selected any PID (provided that I have rights to access the process information) - is there a way I can wait for the PID to finish and get its exit code?

+6
source share
3 answers

You can use strace , which tracks signals and system calls. The following command waits until the program is completed, then prints the 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 also printed. In any case, you will need to use sed if you want to use the exit code in a shell script.

If this is too much shell code, you can use a program that I cracked together in C some time ago. It uses ptrace() to catch signals and exit codes from pids. (It has rough edges and may not work in all situations.)

I hope this helps!

+6
source

is there a way that I can wait for the completion of the PID and get its exit code

Yes, if the process is not ptrace d someone else, you can PTRACE_ATTACH to it and receive notifications about various events (for example, received signals) and its output.

Beware, it is quite difficult to handle it correctly.

+3
source

If you know the process ID, you can use the wait command, which is bash builtin:

 wait PID 

You can get the PID of the last run of the command in bash with $! . Or you can grep for it with ps output.

In fact, the wait command is a useful way to run the parralel command in bash. Here is an example:

 # Start the processes in parallel... ./script1.sh 1>/dev/null 2>&1 & pid1=$! ./script2.sh 1>/dev/null 2>&1 & pid2=$! ./script3.sh 1>/dev/null 2>&1 & pid3=$! ./script4.sh 1>/dev/null 2>&1 & pid4=$! # Wait for processes to finish... echo -ne "Commands sent... " wait $pid1 err1=$? wait $pid2 err2=$? wait $pid3 err3=$? wait $pid4 err4=$? # Do something useful with the return codes... if [ $err1 -eq 0 -a $err2 -eq 0 -a $err3 -eq 0 -a $err4 -eq 0 ] then echo "pass" else echo "fail" fi 
0
source

Source: https://habr.com/ru/post/911772/


All Articles