2014-10-28 41 views
0

我在C中有下面的程序,它应该作为deamon运行,并且无论什么时候写入到FIFO中的东西,它都应该将它写入文件中。C linux守护进程在打开FIFO后没有写入文件

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <string.h> 
#include <signal.h> 
#include <syslog.h> 

#define BUF_LENGTH 255 

volatile int signal_flag = 1; 

void signal_handler(int sig) 
{ 
    signal_flag = 1; 
} 

char *getTimeString() 
{ 
    time_t rawtime; 
    struct tm * timeinfo; 

    time (&rawtime); 
    timeinfo = localtime (&rawtime); 
    char *timeStr = asctime (timeinfo); 
    timeStr[strlen(timeStr) - 1] = 0; 

    return timeStr; 
} 

void printUsage() 
{ 
    printf("Usage: syslog_daemon PATH INTERVAL\n"); 
} 

int main(int argc, char *argv[]) 
{ 
    /* print usage */ 
    if(argc != 3) 
    { 
     printUsage(); 
     exit(EXIT_SUCCESS); 
    } 

    /* process arguments */ 
    char *logFilePath = argv[1]; 
    int interval = atoi(argv[2]); 

    /* establish the signal handler */ 
    struct sigaction action; 

    sigemptyset(&action.sa_mask); 
    action.sa_flags = 0; 
    action.sa_handler = signal_handler; 
    sigaction(SIGALRM, &action, NULL); 

    /* initialize variables */ 
    int fd; 
    /*char buf[BUF_LENGTH]; 
    int length;*/ 
    int msgs = 0; 

    /* Create FIFO if not created */ 
    if (mkfifo("/tmp/pb173_syslog", 0766) == -1 && errno != EEXIST) 
    { 
     fprintf(stderr, "Making FIFO failed with error %d\n", errno); 
     exit(EXIT_FAILURE); 
    } 

    /* Run */ 
    daemon(1, 1); 
    while(1) 
    {   
     /* Open FIFO */  
     fd = open("/tmp/pb173_syslog", O_RDONLY); 
     close(fd); 

     /* Open and write into file */ 
     FILE *f = fopen(logFilePath, "a"); 
     fprintf(f, "Daemon write: %d\n", msgs); 
     fclose(f); 


     /* Process SIGALRM and write syslog */ 
     if(signal_flag) 
     {     
      openlog("syslog_daemon v2", LOG_CONS, LOG_DAEMON); 
      syslog(LOG_INFO, "Messages written: %d\n", msgs); 
      closelog(); 

      msgs++; 

      signal_flag = 0; 
      alarm(interval); 
     } 
    } 

    return 0; 
} 

但是这个程序不会写入任何文件。看来,当FIFO打开时,它不能在任何地方写入。但是如果我不打开FIFO,程序将毫无问题地写入文件。有谁知道这是什么问题?谢谢你的帮助。

+2

您的程序是否在开放系统调用时阻塞?如果是,那么确保你在两端打开fifo。如果fifo未在读取和写入时打开,则开放系统调用会进入阻止模式。 – 2014-10-28 16:54:54

+0

您打开FIFO,然后立即关闭它而不读取任何内容。你的守护进程如何得到任何东西写入辅助文件? – 2014-10-28 17:28:56

回答

3

它挂在open试图打开没有第二个端点(作家)连接的FIFO。 您可能想要使用O_NONBLOCK

下面是strace输出报价,其中显示出它挂起:

$ strace -p 23114 
Process 23114 attached - interrupt to quit 
open("/tmp/pb173_syslog", O_RDONLY 

如果你写的东西到FIFO(例如echo test > /tmp/pb173_syslog)它放开并开始工作。