tags:

views:

91

answers:

5

I need to kill such user processes that are taking longer time than a said expected interval on UNIX (Solaris) operating system. This needs to be done inside the process that is currently being executed.

Please suggest how this can be achieved in C or in UNIX?

+7  A: 

See the alarm() system call. It provides you with a SIGALRM signal which your process can handle, and use to quit.

Oli Charlesworth
You don't even need to handle it - the default action of `SIGALRM` is to terminate the process.
caf
I will handle the SIGALRM so as to kill my process gracefully
Sachin Chourasiya
A: 

At one time I had to solve this exact same problem.

My solution was as follows:

Write a controller program that does the following:

  1. Fork a child process that starts the process you want to control.
  2. Back in the parent, fork a second child process that sleeps for the maximum time allowed and then exits.
  3. In the parent, wait for the children to complete and whichever finishes first causes the parent to kill the other.
David Harris
Cute...but I think setrlimit() is more direct.
Drew Hall
A: 

There's an easier way. Launch a worker thread to do the work, then call workerThread.join(timeoutInMS) in the main thread. That will wait for that long. If that statement returns and the worker thread is still running, then you can kill it and exit.

dj_segfault
Isn't this Java?
Oli Charlesworth
Ugh. My apologies for Stacking too late at night. Totally misread it.
dj_segfault
+2  A: 

As long as killing without warning the process in overtime is acceptable, one alternative is to use ulimit -t <time> at the time of launching the process.

Pascal Cuoq
+2  A: 

With setrlimit, you can limit the amount of CPU time used by the process. Your process will receive a SIGXCPU once the limit is exceeded.

#include <sys/resource.h>
struct rlimit limits = {42, RLIM_INFINITY};
setrlimit(RLIMIT_CPU, &limits);
Gilles