andrewarnier
andrewarnier

Reputation: 177

how to run perl program automatic when the perl program isn't running?

i have run a perl program like a deamon, perl check.pl &

now,i can check the perl program running state,but how to modify the shell script to running the perl program when the perl program isn't running ?

    a=`ps -ef | grep "perl" | grep "check" |awk '{print $2}'`
    for p in $a
    do
      echo perl
      echo $p
   done

Upvotes: 0

Views: 90

Answers (2)

clt60
clt60

Reputation: 63892

So,

  • i have run a perl program like a deamon, perl check.pl &

This, isn't like a daemon, but an simple background process. Every process has an parent process. The background process (like the above) has as a parent the "bash" what sends it into the bakcground, so the bash can wait for it's termination. The daemon has parent process the process called init, with the PID == 1 and therefore it is watched by the init.

  • now,i can check the perl program running state,

Yes, as you can check any other program's state. One comment, doing such grep on program names coukd have some strange side effects, like:

$ perl log.pl &

Now, grepping the output of the ps will lead to two, "log" processes, which one of them will be the syslogd process. Of course, youre in your example limited this with an another grep to perl only, but at the cost of two processes.

You can limit two processes to one, using some smarter grep argument, like

ps -ef | grep 'perl check'

the above would search with one process, the string "perl check". Unfortunately, this will find the grep process itself, like

$ perl check.pl &
$ ps -ef | grep 'perl check
  501 45063 42171   0 11:26   ttys001    0:00.00 grep perl check
  501 45002 44504   0 11:21   ttys002    0:00.02 perl check.pl

One nice workaround is using a sting like

grep '[p]erl check'

like

$ perl check.pl &
$ ps -ef | grep '[p]erl check'
  501 45002 44504   0 11:21   ttys002    0:00.02 perl check.pl
  • but how to modify the shell script to running the perl program when the perl program isn't running ?

If the grepping the outout of ps returns nothing, you should start the script. You should check the content of your a (you really should give it better name as a, like perlPID or such). If the length of the argument of -z is zero, it returns "true", so:

[[ -z "$a" ]] && perl check.pl &

Upvotes: 1

mpapec
mpapec

Reputation: 50637

You can leave running check to perl itself, and call it regularly via system crontab,

use Fcntl ':flock';
flock(DATA, LOCK_EX|LOCK_NB) or die "Already running..\n";

# ...


__DATA__

Upvotes: 1

Related Questions