Sunday 13 December 2015

Linux Daemon Process

Q:- Create a daemon process in linux to write the numbers 1-10 to text file. Use C programming language.



Code:-

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<stdlib.h>
int main()
{
pid_t pid=0;
pid_t sid=0;
int i=0;
FILE *fp =NULL;

pid=fork();

if(pid<0)
{
printf("Fork failed!!");
exit (1);
}

if(pid>0)
{
printf("The pid of child process %d",pid);
exit (0);
}

umask(0);
sid= setsid();

if (sid<0)
exit (1);

close (STDIN_FILENO);
close (STDOUT_FILENO);
close (STDERR_FILENO);

fp=fopen("mydaemon.txt","w+");
while(i<10)
{
sleep(1);
fprintf(fp,"%d",i);
i++;
}

fclose(fp);

return 0;
} 
 

Output


[root@daemon] ls
abc.txt  cpu.txt   daemon.c~    dictionary  mst           ssh.sh~   tbt.txt
a.out    cpu.txt~  daemon.txt   e2.txt      mydaemon.txt  ssh.txt   unix
avl      daemon.c  daemon.txt~  e2.txt~     ssh.sh        ssh.txt~
[root@daemon] gcc daemon.c
[root@daemon] ./a.out
The pid of child process 1938
[root@pict b] cat mydaemon.txt
0123456789
[root@daemon]

No comments:

Post a Comment