C - Library functions - Using daemon()

In this tutorial we will see the daemon() function.
This function is designed to launch a program in background.

So when you exectute a program it will start and if you want to stop it, just make a Ctrl + C.

The program will stop instantly.

Now, with the daemon function, the program will not stop even with a Ctrl + C.
To stop it, you have to kill the process with the kill command.

Let's see an example of the daemon() function:

#include <unistd.h>
#include <stdio.h>

int     main()
{
  daemon(1, 1);
  while (89)
    printf("Lol\n");
}

How to see, if the daemon is still running?

We can use the top command:

$ top

You will see all process running.

If you execute our program with daemon, you will see the a.out command even if you close your terminal.

To stop it, you have to check the pid of the a.out command, then:

$ kill theNumber

Note that you can make a daemon without the daemon() function in your code.

Indeed, just add the & character after the name of your executable and you will have a daemon of your program:

$ ./a.out &

 

Comments

Comment: 

The & character does not make it a daemon process. It makes the program execute in the background, but it can still be controlled from your terminal - e.g., type 'fg' to bring it back to the foreground. A daemon process has not stdin/stdout/stderr to be controlled from.

Comment: 

Hello Bruce,

Thank you for the precision. smiley

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.