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:
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 theprocess.o
(Killing the process works, but it doesn't restart it)
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);
}
}