Search code examples
clinuxbashapplication-restart

Restart C program from Bash terminal


I've been working on my school project and I've been stuck on this step for a few days now. Any kind of help would be highly appreciated!  

What I've tried so far:  

  • Compiling the script. It compiles correctly and I'm able to run it by typing ./process.o, however I cannot make it so when I kill it, it restarts. I've been googling and trying various things but nothing seems to work, it always kills the process but doesn't restart it.
  • kill -SIGKILL (PID)
  • kill 2 (PID)
  • kill 1 (PID)
  • kill -HUP 3155
  • Various other commands that only killed it, nothing seems to work. Do I have to modify the code or something? I'm deeply confused.  

Here's what I have to do:

Make a new file with C. Save it with name process.c (Did this)

#include <stdio.h> 
#include <unistd.h> 

int main() { 
  printf("Creating a background process..\n"); 
  pid_t pid = fork(); 

  if (pid > 0) return 0; /* Host process ends */ 
  if (pid < 0) return -1; /* Forking didn't work */ 

  while(1) { } /* While loop */ 
  return 0; 
}

Compile the following code to working program called process.o and start the process. (Did this, works to this point)

Use a kill command which restarts the process.o (Killing the process works, but it doesn't restart it)


Solution

  • You need to keep the parent process running to monitor the child process. If the parent detects that the child is no longer running, it can restart it.

    The parent can use the wait system call to detect when the child exits.

    while (1) {
        pid_t pid = fork();
        if (pid < 0) {
            return -1;
        } else if (pid > 0) {
            // parent waits for child to finish
            // when it does, it goes back to the top of the loop and forks again
            wait(NULL);
        } else {
            // child process
            while (1);
        }
    }