进程的 pid 显示在终端中,但未在根目录中创建日志文件。请仔细阅读此代码并告诉我缺少什么。
终端输出:
process_id of child process 5611
来源如下。
#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);
}