2

I'm writing some automation scripts, in which I need to kill some processes.

Previously I would usually use kill -9 pid to kill processes but once upon a time, I notice that when I used kill -9 to kill some tcpdump processes:

For example:

tcpdump -i eth0 -w output.pcap

The captured packets were not put into output.pcap and it was empty. But if I used kill, it worked fine.

For some processes, like ./prog >> test_log, I'm afraid if I use kill -9 to kill the processes the output won't get redirected to test_log.

I'm also afraid if I use kill without -9 the kill command may fail.

Can anyone tell me how to properly use kill so that the killing doesn't cause problems with the output file and I'm able to kill the processes without issue?

slm
  • 369,824
misteryes
  • 1,333

2 Answers2

3

If a process does not write to a terminal but uses redirection instead (or even when explicitely writing to a file) then buffering may be an issue. Have a look at stdbuf and unbuffer (expect) or search here for them.

Your tcpdump problem can be solved (or reduced) by the -U flag.

In general you should kill this way:

kill $PID; sleep $wait; kill -9 $pid &>/dev/null

kill / kill -TERM gives the process the chance to cleanly finish (including e.g. flushing buffers and closing file descriptors) whereas kill -KILL just removes the process from memory and the process list which is always a risk with non-atomic operations which may be in progress right then.

Hauke Laging
  • 90,279
1

You should start out with issuing a kill order of 15 wait, if not terminated, kill 2, etc.

In general, normal running, with exceptions, it is not the best sign if a program does not end after kill 15,2,1. Though you can't expect it to end immediately.

Secondly it depends on the specific program you kill. Some programs catch and clean up, others should have done it but don't, others has nothing to clean up and leave up for the OS to clean up after it. Etc.

You should also (always) check if there is other signals you can send to the application or if it is a deamon, by which you usually have a start/stop script etc.

Also see:

Runium
  • 28,811