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,程序將毫無問題地寫入文件。有誰知道這是什麼問題?謝謝你的幫助。
您的程序是否在開放系統調用時阻塞?如果是,那麼確保你在兩端打開fifo。如果fifo未在讀取和寫入時打開,則開放系統調用會進入阻止模式。 – 2014-10-28 16:54:54
您打開FIFO,然後立即關閉它而不讀取任何內容。你的守護進程如何得到任何東西寫入輔助文件? – 2014-10-28 17:28:56