0

How can I shut down a linux program in C. I'm editing a script to have a timer thing where the script only runs for 10 seconds then shuts down.

The line I'm running is: ./startmerge

It's a C code to merge all my server files together that I downloaded, but I only want it to be running for 10 seconds.

  • A common method is to use a watch dog timer, running as another process. When your script starts, save the PID generated -- then have your watch dog keep an eye on that, sending the kill signal if needed. – Jeremy J Starcher Dec 22 '13 at 05:37
  • What do you want to happen if it hasn't finished what it's supposed to do within 10 seconds? – Bandrami Dec 22 '13 at 05:38
  • 1
    `alarm(10)` is pretty simple though it may not be the way your really want to go. Note you will need to write a little signal handler for it because the default disposition is to terminate the process. – Duck Dec 22 '13 at 05:40

1 Answers1

3

If most of the time is spent in computing with the CPU (in other words, if the 10 seconds in ./startmerge are not spent on IO) then you want to limit the CPU time, so use the setrlimit(2) syscall with RLIMIT_CPU. In bash, you want to use its ulimit builtin (calling setrlimit syscall), see this answer, like

  ulimit -t 10

before running startmerge.

If your startmerge is not CPU intensive, you want to kill it after 10 seconds, perhaps (see this)

  startmerge & ; pidof_startmerge=$!
  sleep 10; kill $pidof_startmerge

Better yet, make that a loop (e.g. loop ten times around a sleep 1)

If you have access to the C source code of startmerge and want to improve it, read first time(7) and signal(7). As Duck commented, consider alarm(2) or setitimer(2) or timer_create(2) and set up a signal handler -e.g. for SIGALRM with sigaction(2) (but don't forget that signal handlers are limited to calling async-signal-safe functions only; you could set a global volatile sig_atomic_t variable in them, and test that variable outside). If your startmerge has some event loop based upon some multiplexing syscall like poll(2) (or the old select(2)) it should even be simpler, and the Linux specific timerfd_create(2) could be very helpful.

You could trap SIGALRM in bash, see this.

Advanced Linux Programming has some chapters related to your question. Advanced Bash Programming Guide is also useful to read.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547