2013-10-16 54 views
1

我已经创建了一个网络守护进程,但由于某些原因代码没有打印到日志文件。如果不在那里创建文件,我会从stdout中获取信息,以便过程通过这些函数。守护进程没有输出到文件,但没有显示错误

process_id of child process 7796

13254864UDP Server: waiting for connection...

我想记录到文件中不SYSLOG如果在所有possoble。

#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); 
} 

回答

2

输出到您的文件可能被缓冲。尝试在您希望看到(立即)写入日志文件的fprintf调用之一后添加fflush(logging_file)

+0

我的假设是,如果你有一个换行fprintf它自动刷新自动。 – GeneralZero

+0

但似乎并非如此。因为fflush不起作用,所以我把setbuff(logging_file,NULL);. 你碰巧知道这是为什么?也许是因为日志文件是FILE *? – GeneralZero

+0

缓冲的类型(默认情况下)通常由目标的类型决定(例如,交互式tty与文件)。见http://stackoverflow.com/questions/5229096/does-printf-always-flush-the-buffer-on-encountering-a-newline –