我的守护进程代码在终端中完美执行,但是没有创建日志文件

时间:2013-09-12 19:46:25

标签: c ubuntu-12.04 daemon

进程的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);
}

2 个答案:

答案 0 :(得分:0)

作为Henry Spencer once put it

  

如果发布函数以在发生时返回错误代码   困难,你要检查那个代码,是的,即使是   检查你的代码大小的三倍,并在你打字时产生疼痛   如果你说“你不能发生在我身上”,众神就是这样的   肯定会因你的傲慢而惩罚你。

fp = fopen ("log.txt", "w+");
fprintf(fp, "Logging info...\n");

您正在使用fp而未检查fopen()是否实际返回了有效指针。 如果fopen()返回空指针,则可以检查errno的值以查看出现了什么问题。

答案 1 :(得分:0)

正在创建日志文件。您需要以root身份运行代码,因为日志文件在'/'目录中打开,通常只能由root访问。