Issue
I have a simple server client test. I start the server as a background process, wait for 5 seconds and then start the client. Like so
server > /tmp/serverlog 2>&1 &
sleep 5
client > /tmp/clientlog 2>&1
ret=$?
cat /tmp/serverlog
cat /tmp/clientlog
exit ret
Sometimes, the server will fail to start. In that case, I want to exit with the exit code from the server and not start the client.
I can check if the server is alive with kill -0
. But I can't get the exit code. I can use wait
to wait for the server to finish but if the server doesn't fail, then wait
will never return.
How can I check if the background server process died and get the return code only if it died?
Solution
Use kill -0
to see if the server died, and if it did, then use wait
to get its exit status.
server > /tmp/serverlog 2>&1 & server_pid=$!
sleep 5
if ! kill -0 $server_pid; then
wait $server_pid
exit # uses exit status of previous command, which is exit status of server
fi
client > /tmp/clientlog 2>&1
ret=$?
cat /tmp/serverlog
cat /tmp/clientlog
exit $ret
It shouldn't be a real issue, but be aware of the race condition of the server's process ID being available for reuse after it exists, but before you use it with kill
and wait
.
Answered By - chepner Answer Checked By - Candace Johnson (WPSolving Volunteer)