我想在设置的几秒钟后重新启动程序

问题描述 投票:0回答:1

目前,我试图为我的项目做看门狗。

另外,我想设置一个重启计时器。

我的意思是,如果过了几秒钟,程序将从头开始。

当然,我可以在主函数中使用while循环。我不要这个。

我只想制作一些类,例如计时器或看门狗,

在主功能经过我设置的时间后,我想让我的程序再次启动。

有什么好主意吗?

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;
}
c++ timer restart watchdog
1个回答
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 now\n");
         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,并且要实施的工作要多得多。

© www.soinside.com 2019 - 2024. All rights reserved.