我在C中有以下程序,它应该作为守护程序运行,每当写入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,程序会毫无问题地写入文件。有谁知道这是什么问题?谢谢你的帮助。
答案 0 :(得分: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
),它会解锁并开始工作。