如何知道 运行 后台进程是否核心化

How to know if a running background process cored

我有一个过程 myprocess,我从脚本中 运行。是否可以检查此进程是否执行成功或崩溃?

这是我的脚本的样子

myprocess 12 &
sleep 12
# I want to check here if the process crashed

我运行在后台设置进程的原因很简单。我想在 sleeping 之前完成其他任务。醒来后,我想看看进程是正常退出还是崩溃(dumped core)。

PS:如果需要任何其他详细信息或更多代码,请在下方评论。

假设您没有 $PWD 上名为 core 的文件(否则它将被删除),这是 偷懒 方法:

(请注意 this [lazy 核心文件方法 only] 假设正确sysctl fs.suid_dumpable if myprocess 的参数化将有它的 privilege levels changed or is execute only. Also note that kernel.core_pattern settings may cause the core file to be dumped somewhere else and not at $PWD. See this article 以便正确设置它。感谢@alvits 指出这两个潜在问题。无论如何,我不真的很推荐使用下面核心文件的做法.)

#!/bin/bash

rm -f core
ulimit -c unlimited

myprocess 12 &

# ... Do your stuff ...

sleep 12

if [ -f core ]; then
    echo "This is a minimal example to show that the program dumped core."
fi

另请注意,这仅在同时没有其他任何东西将核心转储到 $PWD

时才有效

一个清洁器方法:

#!/bin/bash

(rm -f /tmp/myprocess.success && myprocess 12 && touch /tmp/myprocess.success) &

# ... Do your stuff ...

sleep 12

if [ -f /tmp/myprocess.success ]; then
    echo "myprocess returned EXIT_SUCCESS. But if it didn't returned before sleep 12 elapsed, this will fail."
fi

正确的方法:

#!/bin/bash

myprocess &

# Store myprocess PID
MYPROCESS_PID="$!"

# ... Do your stuff here ....

# Wait until myprocess returns
wait "${MYPROCESS_PID}"

# Store myprocess exit status (returned by wait)
$ret="$?"

if [ "${ret}" -gt 0 ]; then
    echo "Myprocess didn't exited with EXIT_SUCCESS"
fi