How to get the program to terminate after sertain length of time?
Hi!
I want my program to run for 5 minutes (or any other length of time), during which it will be doing a task, then it must terminate after 5 minutes or any other length of time. Is there such function that allows time setting? I am not shure, but would time() or timer() functions be used for this? Tnanks |
Hi -
Probably the easiest way is to use a shell script: 1. The script starts the program in the background (&) and saves the PID ($!) 2. The program executes while the script sleeps N seconds 3. At the end of N seconds, the script does a "kill $!" Here's an example: Code:
MYPROG & http://www.cs.usfca.edu/benson/cs326.../src/sigalrm.c 'Hope that helps .. PSM |
U might be able to use the time function as well. if doing it in C of course. U could get the current time and then add 5 min to it then have a while loop check it every tick till it matches the correct value.
This might be problematic and there is probably a better way like paul said above. |
Thanks, sorry I forgot to mention, I'm using C.
|
Just throwing out another option...
You could make the program multi-threaded. Create a thread that just sleeps the desired amount of time, and then communicates in some manner (global variable, a system "kill" command, or whatever) that time is up to the other thread(s). It's basically the same as paulsm4's sigalarm example. For me, I never became comfortable with signals and generally avoid them. That's just me though. |
The problem with having the program monitor its own time is that if the program runs wild you can't trust the monitoring.
You might want to do it from outside the program, perhaps using a shell script that runs maybe once a second until a time condition on the program being monitored is satisfied. When that time condition is satisfied, the shell script kills the program and exits. Perhaps something like this: Code:
progID="myprog" |
Since I became amused by this script, I wrote another variant of it. This variant runs on wallclock time. It starts the program and kills it after a specified number of seconds.
It could be made more efficient; I should call up the current time just once at the beginning and once each time through the loop, saving it into a variable, then extracting hours minutes and seconds via awk. Code:
#!/bin/bash |
All times are GMT -5. The time now is 04:23 PM. |