我创建了一个网络守护程序,但由于某种原因,代码没有打印到日志文件中。如果不存在该文件,则会创建该文件,并且我确实从标准输出获取信息,因此该过程确实通过了这些功能。
process_id of child process 7796
13254864UDP Server: waiting for connection...
如果可能的话,我想记录到一个不是 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);
}