我想在我设置的几秒钟后重新启动我的程序
I want to restart my program after the few seconds what I set
目前,我尝试为我的项目制作一个看门狗。
另外,我想制作一个重启计时器。
我的意思是,如果几秒钟过去了,程序将首先启动。
当然,我可以在主函数中使用 while 循环。我不要这个。
我只想做一些类,比如计时器或看门狗,
在 main 函数通过我设置的时间后,我想让我的程序重新启动。
有什么好主意吗?
int main(void)
{
Timer timer(5) // setting my timer to 5 secs
//If time takes over the 5 secs in this loop,
//I want to restart the main loop.
while(1)
{
//Do Something...
}
return 0;
}
如果你能让你的代码关注时钟,并在这么多秒过去后自愿返回,这通常是最好的方法; 但是,由于您提到了看门狗,听起来您不想相信您的代码可以做到这一点,因此(假设您有一个支持 fork((的操作系统(您可以生成一个子进程来运行代码, 然后父进程可以在 5 秒后单方面 kill(( 子进程,然后启动一个新进程。 下面是一个示例,子进程每秒计算一个随机数量的土豆;如果它尝试计数超过 5 个,它将被父进程杀死。
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
// The code you want to be able to abort and restart would go in here
static void FunctionThatMightTakeALongTime()
{
srand(time(NULL)); // just so we get different random values each time
const int countTo = (rand()%12)+1;
for (int i=0; i<countTo; i++)
{
printf("%i potato... (out of %i)n", i+1, countTo);
sleep(1);
}
}
int main(int argc, char ** argv)
{
while(1)
{
pid_t pid = fork();
if (pid == -1)
{
perror("fork"); // fork() failed!?
return 10;
}
else if (pid == 0)
{
// We're in the child process -- do the thing
printf("Starting child process...n");
FunctionThatMightTakeALongTime();
printf("Child process completed!n");
return 0;
}
else
{
// We're in the parent/watchdog process -- wait
// 5 seconds, and then if the child process is
// still running, send it a SIGKILL signal to kill it.
// (if OTOH it has already exited, the SIGKILL isn't
// required but it won't do any harm either)
sleep(5);
printf("Watchdog: killing child process nown");
if (kill(pid, SIGKILL) != 0) perror("kill");
// Now call waitpid() to pick up the child process's
// return code (otherwise he'll stick around as a zombie process)
if (waitpid(pid, NULL, 0) == -1) perror("waitpid");
}
}
}
注意:如果您的操作系统不支持fork()
(即您的操作系统是Windows(,这种技术仍然是可能的,但它需要使用特定于Windows的API,并且要实现更多的工作。
相关文章:
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- 如何使用 ctypes 停止和重新启动从 Python 运行的C++代码
- 重新启动后,线程无法在 while 循环中再次运行
- 在程序和基于文本的游戏和C++内重新启动程序
- 在程序/基于文本的游戏/C++内重新启动程序
- 为什么使用 exec() 重新启动程序不能正常工作?
- 即使在我关闭应用程序并重新启动它后,如何保持我的 ID 被阻止?
- 有没有办法在不重新启动或注销的情况下加载游标?
- IO服务重新启动后,Boost最后期限计时器持续触发
- 在C++中重新启动随机数序列
- 稍后在构造函数中重新启动异常指令删除此指令
- 如何获取代码::块以在代码::块重新启动后保持库的配置?
- 我想在我设置的几秒钟后重新启动我的程序
- 如何使重新启动此循环,当用户输入 1 时,并在 0 时停止
- UDP 服务器每 5 秒重新启动一次
- 有没有办法检查内存缓存是否已重新启动?
- (Windows 10) 在不更新的情况下重新启动C++
- Live555MediaServer 在每个新连接时重新启动流。为什么将"reuseSource"设置为 true 无法按预期工作?
- OpenGL和SFML时钟未正确重新启动
- 程序终止几秒钟后重新启动