• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 809
  • Last Modified:

Shell script tp kill a process

I have a php script that I'm runnign via cron.  Sometimes it exits when finished and sometimes it hangs..  I have no idea why, it runs and exits via a sheel and runs then exits thru Zend Studio using my server as to debug.

The script goes out and index's anythign new on youtube in certain categories.  How can I insure the php script die's before the next cron job starts?  Is there a way to do this in a php or a shell script?   I have 3 php files that run, one per hour..  all three have the eextension _auto.php

I'd like to search running processes and if _auto.php is found, killl the process..  I don't know enough about shell scripts to do that and my googl searches have come up empty.  Or is it better to let the php script first check for another copy running and kill it if it is?
3 Solutions
The attached script will kill all processes containing _auto.php

To break it down:-

ps ax lists all processes - the PID is the first field
grep _auto.php searches for lines containing _auto.php
awk {'print $1'} returns the first field (in this case the process ID)

So adding the for loop, it loops over the process IDs and runs kill -9 on each of them
for i in `ps ax | grep _auto.php | awk {'print $1'}`; do kill -9 $i; done

Open in new window

try this

kill -9 `ps -ef | grep _auto.php | awk '{ print $2 }'`


kill -9 `ps -ef | grep -v grep | grep _auto.php | awk '{ print $2 }'`
Hi megarry,

its not very nice to do such things. It will work to just kill by grepping through the whole process-list, but maybe you can think of future more complex situations.

Modern Unices do solve this matter in a prettier, more efficient and safer way. So why not follow the best practice?

Change the PHP cronjob so it writes a PID file and terminates (SIGTERM = 15) any the latest process? See code snippet.

Maybe this is not a "shell" solution, but think about it anyway ;-)

   * You should probably create a folder like "/var/run/myapplication"
   * and give correct file permissions to the user running the cron-job!
  $PID_FILE = '/var/run/myapplication/myappliation.pid';
  $SIGTERM = 15;
  $pfh = @fopen($PID_FILE, 'a+');
  $old_pid = (int)@fgets($pfh);
  if ( $old_pid > 0 ) @posix_kill($old_pid, $SIGTERM);
  @ftruncate($pfh, 0);
  if ( @fwrite($pfh, posix_getpid()) === false ) {
    echo "ERROR WRITING TO PID FILE. Check permissions!\n";
  for ($i = 1; $i > 0; $i++) {
    echo "Hello World! (".$i.")\n";

Open in new window

megarryAuthor Commented:
I liked the PHP one best because I can include this in my app and as you said, not have to cycle thru the process list.

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now