开发者

Is there a way to stop and resume a C program

I am doing a project in C and in that I need to process a lot of data . Is there a way to stop the program automatically after 30 minutes and then resume whenever I ru开发者_StackOverflow社区n the program again?


There is no automatic way to do this. If you're on a Unix system though, you can press Ctrl+Z while your program is running to send it a STOP signal. It will wait until you continue again by sending it a CONT signal (the easiest way is with the fg shell command). A stopped process is still resident in memory, but is not running.

There are more sophisticated ways to take a "snapshot" of a running program and save it to disk. Later, you can load the snapshot and continue execution of the program. For example, see CryoPID.


You could automate it. The Crtl-Z and fg are, as already mentioned, nothing more than signals. In Unixes you can send them with the kill command. So kill -19 $PID will stop your process (when $PID is its PID) and kill -18 will continue it.

You just have to write a wrapper script, that looks like:

#!/bin/sh

PIDFILE=wherever/myprogram.pid

if [ -e $PIDFILE ]; then
  kill -18 `cat $PIDFILE`
else
  myprogram &
  echo $! > $PIDFILE
fi

sleep 30
kill -19 `cat $PIDFILE`

(very short, untested, you have to take care to remove the pidfile when you kill the process). First time you run it, it will start the execution (for 30 seconds), the later times it will just revoke your program. You could improve it e.g by checking in the beginning if there is a process of your program in the process list, and if not remove the pidfile in case it is already there. So it would even behave correct after reboot or termination of your process.


Short answer: Without putting in some effort to have your program 'hibernate itself', no.

If you're running on UNIX then I'm sure you can set up a cron job to suspend / resume the program as and when needed. Under Windows you'll be afforded no such luxury.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜