Originally Posted by
HalNineThousand
Is there any way, from within a C or C++ program, on Linux, for the program to detach itself from the console and operate as a daemon and be independent of the console instance from which it was started?
Of course. The basic steps:
Code:
#include <unistd.h>
pid = fork();
if(pid < 0)
{
/* Report error and exit */
}
if(pid == 0)
{
/* The child becomes the daemon. */
/* Detach all standard I/O descriptors */
close(0);
close(1);
close(2);
/* Enter a new session */
setsid();
/* We are now daemonized */
run_the_daemon();
exit(0);
}
else
{
/* The parent need not exist anymore */
exit(0);
}