Killing a process that takes too long

Hello,
I have a C program that takes anywhere from 5 to 100 arguments and I'd like to run it from a script that makes sure it doesnt take too long to execute. If the C program takes more than 5 seconds to execute, i would like the shell script to kill it and return a short message to the user. If it takes less than 5 seconds, the program spits out a short message to standard out, then i'd like the script to stop normally.

Can a script help do this?, or am I going to have to rewrite the C program to handle this?

The problem is, it seems like i would need a multi-threaded shell script?...I'm really not sure how to go about doing this. Any help would be greatly appreciated. I'm running bash 3.00.15 on redhat.

Thanks

Try this if you don't want to change your c program

#!/usr/bin/perl -w

my $timeout = 5; # 5 sec timeout

eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm $timeout;
qx(./mah.ksh);
alarm 0;
};

if ($@) {
die unless $@ eq "alarm\n";
print "timeout\n";
qx(ps -ef | grep mah.ksh | egrep -v " grep | vi | more | cat | pg | egrep " | awk '{print \$2}' | xargs kill );
}
else {
print "no timeout \n";
}

replace mah.ksh with your c program name.

Thanks...that script works great :slight_smile:

Although I'm still having problems...I modified your perl script to be able to take command line arguments...is there a faster way than the way I did it?

The main problem however is that whenever I have php4's shell_exec command calling this script, nothing that is printed via perl's qx command gets returned to php4...i tried 'system($command)' rather than 'qx($command)', but that doesn't help...interestingly though, 'print system($command)' returns a -1 to php, but from a terminal, all of those run the program as desired...

how can i get shell_exec to see output from a call to qx?...is qx opening a new stream each time it is called or something?

here's my perl modified script:

#!/usr/bin/perl -w

# Run my_program w/ the given arguments.  If my_program is still running 
# after the specified number of seconds, kill it, and tell the user.

my $timeout = 5; # 5 second timeout

eval {
  local $SIG{ALRM} = sub { die "alarm\n" };
  alarm $timeout;
  $command = "./my_program";
  foreach $argnum (0 .. $#ARGV) {
    $command .= " $ARGV[$argnum]";
  }
  print qx($command);
  alarm 0;
};

if($@){
  die unless $@ eq "alarm\n";
  print "timeout\n";
  qx(ps -ef | grep pokenum | egrep -v " grep | vi | more | cat | pg | egrep " | awk '{print \$2}' | xargs kill );
}

just assign it to some variable.... and then print

my $xyz = qx(unix command);
print $xyz,"\n";