4

I wanted to kill a process and remove a flag indicating that process is running. cron:

00 22 * * 1-5 pkill -f script.sh >log 2>&1 ; rm lock >log 2>&1

This works perfectly when I run it on terminal. But in crontab rm is not running. All I can think of is that whole line after -f flag is being taken as arguments for pkill. Any reason why this is happening?

Keeping them as separate cron entries is working. Also pkill without -f flag is running (though it doesn't kill process as I want pattern to be searched in whole command).

SS306
  • 157
  • 1
  • 3
  • 9

3 Answers3

3

Ran into this problem today and just wanted to post a working example for those who run into this:

pkill -f ^'python3 /Scripts/script.py' > /dev/null 2>&1 ; python3 /Scripts/script.py > /tmp/script.log 2>&1

This runs pkill and searches the whole command (-f) that starts with (regex ^) python3 /Scripts/script.py. As such, it'll never kill itself because it does not start with that command (it starts with pkill).

Azeem
  • 11,148
  • 4
  • 27
  • 40
2

the short answer: it simply killed itself!

my answer explained: if you let a command get started by a crond it'll be executed in a subshell. most probably the line you'll find in ps or htop will look like this:

/bin/sh -c pkill -f script.sh >log 2>&1 ; rm lock >log 2>&1

(details may vary. e.g. you might have bash instead of sh)

the point is, that the whole line got one PID (process id) and is one of the command lines which pgrep/pkill is parsing when using the '-f' parameter. as stated in the man page:

-f, --full
          The pattern is normally only matched against the process name.  When -f is set, the full command line is used.

now your pkill is looking for any command line in your running process list, which somehow contains the expression 'script.sh' and eventually will find that line at some point. as a result of it's finding, it'll get that PID and terminate it. unfortunately the very same PID holds the rest of you command chain, which just got killed by it self.

so you basically wrote a 'suicide line of commands' ;) btw: i just did the same thing today and thats how i found your question.

hope this answer helps, even if it comes a little late

kind regards

3.141592
  • 96
  • 8
0

3.141592 and nanananananananananananaBATMAN's answer is correct. I worked around this problem like this.

00 22 * * 1-5 pkill -f script.[s][h] >log 2>&1 ; rm lock >log 2>&1

This works because script.[s][h](string) is not matched with script.[s][h](regex).

mercy387
  • 1
  • 2