Linux short simple command how to send SIGTERM to a process and SIGKILL if it fails to exist in X seconds?
Asked Answered
T

1

1

How should look the Linux command to send terminate signal to the process/PID and if it fails to exit gracefully after 10 seconds kill it?

My attempt is: "sudo timeout -vk 5 10 kill PIDhere" (-v verbose, -k kill after X seconds) but I am not sure if it is good or how to adjust values or if there is better command that even work with part of the name shown in process COMMAND line. ("ps aux" output)

Tonsillectomy answered 23/2, 2022 at 12:38 Comment(0)
R
0
sudo timeout -vk 5 10 kill PIDhere

Will execute kill, and then attempt to terminate that process if it takes too long. Which shouldn't happen, and presumably isn't what you want (if kill was actually hanging, killing it would not affect your actual process). timeout is useful for capping how long a process runs for, not how long it takes to terminate after receiving a signal.

Instead, I'd suggest starting the process asynchronously (e.g. using & in a shell, but any language's subprocess library will have similar functionality) and then waiting for the process to terminate after you send it a signal. I describe doing this in Java in this answer. In the shell that might look like:

$ some_process &
# time passes, eventually we decide to terminate the process
$ kill %1
$ sleep 5s
$ kill -s SIGKILL %1 # will fail and do nothing if %1 has already finished

Or you could rely on wait which will return early if the job terminates before the sleep completes:

$ some_process &
# time passes
$ kill %1
$ sleep 5s &
$ wait -n %1 %2       # returns once %1 or %2 (sleep) complete
$ kill -s SIGKILL %1  # if %2 completes first %1 is still running and will be killed

You can do the same as above with PIDs instead of job IDs, it's just a little more fiddly because you have to worry about PID reuse.

if there is better command that even work with part of the name

Does pkill do what you want?

Roughrider answered 24/2, 2022 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.