Thursday, 12 September 2013

My daemon code is executing perfectly in the terminal but the log file is not getting created

My daemon code is executing perfectly in the terminal but the log file is
not getting created

The pid of the process is getting displayed in the terminal but log file
is not getting created in the root directory. Please go through this code
and tell me whats missing.
Output on terminal:
process_id of child process 5611
Source is below.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/inotify.h>
int main(int argc, char* argv[])
{
FILE *fp= NULL;
pid_t process_id = 0;
pid_t sid = 0;
int fd,wd,i=0,len=0;
char pathname[100],buf[1024];
process_id = fork();
if (process_id < 0)
{
printf("fork failed!\n");
exit(1);
}
if (process_id > 0)
{
printf("process_id of child process %d \n", process_id);
// return success in exit status
exit(0);
}
umask(0);
sid = setsid();
if(sid < 0)
{
exit(0);
}
chdir("/");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
fp = fopen ("log.txt", "w+");
fprintf(fp, "Logging info...\n");
fflush(fp);
fclose(fp);
sleep(1);
struct inotify_event *event;
fd=inotify_init();
wd=inotify_add_watch(fd,"/osa",IN_ALL_EVENTS);
while(1)
{
i=0;
len=read(fd,buf,1024);
fp = fopen ("log.txt", "w+");
fflush(fp);
while(i<len)
{
event=(struct inotify_event *) & buf[i];
if(event->mask & IN_OPEN)
{
fprintf(fp,"%s:was opened\n",event->name);
}
if(event->mask & IN_MODIFY)
{
fprintf(fp,"%s:file is modified",event->name);
}
if(event->mask & IN_DELETE)
{
fprintf(fp,"%s:was deleted\n",event->name);
}
i+=sizeof(struct inotify_event)+event->len;
}
fclose(fp);
}
return (0);
}

No comments:

Post a Comment