gpt4 book ai didi

c - 守护进程未输出到文件但未显示错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:58 29 4
gpt4 key购买 nike

我已经创建了一个网络守护进程,但出于某种原因,代码没有打印到日志文件中。如果文件不存在,则会创建该文件,我会从标准输出中获取信息,因此该过程确实会通过这些函数。

子进程 7796 的 process_id

13254864UDP 服务器:WAITING连接...

如果可能的话,我想记录到文件 NOT 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);
}

最佳答案

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

关于c - 守护进程未输出到文件但未显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19415016/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com