从 Bash 终端重启 C 程序

Restart C program from Bash terminal

我一直在做我的学校项目,现在我已经在这个步骤上停留了几天了。任何形式的帮助将不胜感激!

到目前为止我尝试过的内容:

这是我必须做的事情:

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)

您需要保持 parent 进程 运行 监视 child 进程。如果 parent 检测到 child 不再是 运行,它可以重新启动它。

parent 可以使用 wait 系统调用来检测 child 何时退出。

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);
    }
}