1

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
$
positoy
  • 39
  • 3

1 Answers1

0

When you run on foreground the interrupt signals generated by the terminal go to the group (parent and child). There is more info about this in the following unix exchange answer.

When running on background the process is not listening to the interrupt signals of the terminal. So pressing ctrl+c has no effect at all.

zomeck
  • 51
  • 4
  • Thanks zomeck. I found what I coded here is not really a daemon. I found a good definition and implementation code for creating a daemon process from here. https://stackoverflow.com/questions/17954432/creating-a-daemon-in-linux – positoy Feb 18 '18 at 09:56