Sachin
Sachin

Reputation: 21891

c/unix: abort process that runs for too long

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?

Upvotes: 1

Views: 407

Answers (5)

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);

Upvotes: 2

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

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.

Upvotes: 2

dj_segfault
dj_segfault

Reputation: 12429

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.

Upvotes: -2

David Harris
David Harris

Reputation: 2340

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.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

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

Upvotes: 7

Related Questions