Command timed out implementation

I have a running service which runs in background.
It execute shell commands by function

system(cmd)

I need to report fail when command execution takes more than 60 seconds.
Parent doesn't need to wait for 60 seconds of time if the cmd execution completed already.

runCommand()
{
  pid_t pid;
  pid = fork();
  if( pid  == 0 )
  {
      system(cmd); exit(0);
  }
  else if ( pid > 0)
  {
    sleep(60);
    childTerminated = waitpid( pid, 0, WNOHANG);
    if( childTerminated == 0 )
    {
      kill(pid, SIGKILL);
      timeout = true;
    }
    else
      timeout = false;
  }
}

I think you better put the 60 second supervision into the child code, i.e. replace the system() with code that installs such a signal / -handler and execve() so it directly receives the signal.
Then in the parent code, you just need to waitpid().
But, to be honest, I do not have much practical experience with such C code...

1 Like

I am actually calling sleep with 1 second in a loop, instead of 60 seconds to check if the command has already completed its execution.

What is cmd?