守护程序未输出到文件但未显示错误

时间:2013-10-16 22:23:35

标签: c logging daemon

我创建了一个网络守护程序,但由于某种原因,代码不会打印到日志文件中。如果不存在,则创建该文件,并且我从stdout获取信息,以便该过程完成这些功能。

process_id of child process 7796

13254864UDP Server: waiting for connection...

如果可以的话,我想登录文件 NOT SYSLOG

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>

FILE* logging_file;

int main(int argc, char* argv[])
{
    logging_file = NULL;

    // INITILIZE DEAMON
    if (geteuid())
    {
        printf("You must run this as root\n");
        exit(1);
    }

    // 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
    if (umask(022) < 0)
    {
        printf("Error chainging umask\n");
        exit(0);
    }

    //set new session
    if((sid = setsid()) < 0)
    {
        // Return failure
        printf("Error setting sid\n");
        exit(1);
    }

    // Change the current working directory to root.
    if (chdir("/"))
    {
        printf("Error Changing Directory");
        exit(1);
    }

    // Close stdin. stdout and stderr
    if(close(STDIN_FILENO) < 0)
    {
        printf("Error Closing STDIN_FILENO\n");
    }

    if(close(STDERR_FILENO) < 0)
    {
        printf("Error Closing STDERR_FILENO\n");
    }
    /*close(STDOUT_FILENO);*/

    // Open a log file in write mode.
    if ((logging_file = fopen("/var/log/udp_daemon.log", "a")) < 0)
    {
        fprintf(stdout, "Error Creating Log file\n");
    }

    fprintf(logging_file, "Started Deamon\n");
        fprintf(stdout,"%d",logging_file);

    //Network initilization

    fprintf(logging_file, "UDP Server: waiting for connection...\n");
    printf("UDP Server: waiting for connection...\n");
    //Main Loop with timers
    while (1)
    {
        // Implement and call some function that does core work for this daemon.

        //Receve Data from socket
        bytes_read = recvfrom(server_fd, buffer, MAXBUF-1, 0, cliaddr, &len);

        //If data is present
        if (bytes_read > 0) {

        }

        //short sleep before next intteration
        usleep(10);
    }
    fclose(logging_file);
    return (0);
}

1 个答案:

答案 0 :(得分:2)

您文件的输出可能已缓冲。尝试在您要查看的fflush(logging_file)次调用之后(立即)将fprintf添加到日志文件中。