Now I got the problem -
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
FILE *fp= NULL;
pid_t process_id = 0;
pid_t sid = 0;
// Create child process
process_id = fork();
// Indication of fork() failure
if (process_id < 0)
{
printf("fork failed!\n");
// Return failure in exit status
exit(1);
}
// PARENT PROCESS. Need to kill it.
if (process_id > 0)
{
printf("process_id of child process %d \n", process_id);
// return success in exit status
exit(0);
}
//unmask the file mode
umask(0);
//set new session
sid = setsid();
if(sid < 0)
{
// Return failure
exit(1);
}
while (1)
{
sleep(1);
printf(" Do Some Task Here\n");
}
return (0);
}
Logic
Make child process orphan and is taken over by the init process.
Call setsid() function to run the process in new session and have a new group. Now child is de-associated with terminal.
How to execute
$ gcc -Wall mydeamon.c -o mydeamon
$ sudo ./mydeamon
PS: Program is not tested so you may need to debug if needed.