I want the exact opposite of this question. I want to know how I can create a process that keeps restarting if it's killed. Could someone give me an implementation example?
For instance, let's assume that I have a simple process that continuously logs a timestamp and an incrementing counter to a log file, like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define FILE_PATH "/home/lincoln/date.log"
int main() {
time_t current_time;
struct tm *time_info;
int counter = 0;
while (1) {
FILE *file = fopen(FILE_PATH, "a");
if (file == NULL){
perror("Failed to open the file");
return 1;
}
// Get the current timestamp
time(&current_time);
time_info = localtime(&current_time);
// Format the timestamp
char timestamp[25];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", time_info);
// Write timestamp and counter to the file
fprintf(file, "%s | Counter: %d\n", timestamp, counter++);
fflush(file);
fclose(file);
sleep(5); // Sleep for 5 seconds
}
return 0;
}
To generate the binary (ELF file), I used the following command:
gcc logger_file.c -o date_test
(Please note that this is just an example. It could be a "hello world" program that keeps printing. I chose logging because I want to observe the effects of it continuously running.)
From the quoted question (correct me if I'm wrong), it's achieved by a parent process that monitors the child process. If the child process is killed, the parent process restarts it. I understand this concept, but I don't know how it's implemented in practice.
Could someone demonstrate how it can be implemented using the provided binary example? (link references to me study more about are wellcome too.)
Please let me know if more information is needed.
EDIT: In my implementation, I'm planning to do it on an embedded device. Basically, in my working environment, I have sysVinit as the startup system and BusyBox v1.23.2 as the toolset on a 3.18.44 kernel running on a armv7 processor (I'm using gcc-12-arm-linux-gnueabi-base
toolchain).