I expect the following code on ubuntu linux to create a daemon process which is child process of systemd and keeps printing "do something".
#include <unistd.h>
#include <stdlib.h>
int main()
{
int pid1, pid2;
int status;
if (pid1 = fork()) {
waitpid(pid1, &status, NULL);
}
else if (!pid1) {
if (pid2 = fork()) {
// use exit. return sometimes stop forking
exit(0);
}
else if (!pid2) {
while(1) {
sleep(1);
puts("do something");
}
}
else {
perror("error occured");
return -1;
}
}
else {
perror("error occured");
return -1;
}
while(1) {
sleep(1);
puts("parent do something.");
}
}
But when I interrupt the parent process, its generated daemon also terminates. The daemon only left alive when I run the code on background. Why is it like this?
Daemon alive when I run on background.
$ ./a.out &
parent do something.
do something
parent do something.
do something
(ctrl + c)
do something
do something
do something
Daemon terminates when I run not on background.
$ ./a.out
parent do something.
do something
parent do something.
do something
(ctrl + c)
// not printing anymore
$