有没有办法等到一个过程结束,如果我不是那个开始它的人?
例如,如果我运行"ps -ef"并选择任何PID(假设我有权访问过程信息) - 有没有办法可以等到PID完成并获得退出代码?
您可以使用strace,它跟踪信号和系统调用.以下命令等待程序完成,然后打印其退出代码:
$ 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 +++
Run Code Online (Sandbox Code Playgroud)
来自的信号^Z,fg也kill -USR1被打印出来.无论哪种方式,sed如果要在shell脚本中使用退出代码,则需要使用.
如果那是太多的shell代码,你可以使用我在C中一起攻击的程序.它用于ptrace()捕获信号和退出pids代码.(它有粗糙的边缘,可能无法在所有情况下工作.)
我希望有所帮助!
Lee*_*ton -1
如果您知道进程 ID,则可以使用waitbash 内置命令:
wait PID
Run Code Online (Sandbox Code Playgroud)
您可以使用 获取 bash 中运行的最后一个命令的 PID $!。或者,您可以使用 grep 从 的输出中查找它ps。
事实上,wait 命令是在 bash 中运行并行命令的一种有用方法。这是一个例子:
# 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
Run Code Online (Sandbox Code Playgroud)