如何解决在守护进程中登录到文件
我正在遵循一个快速指南,该指南是如何在C中创建守护进程的,该过程是对Stack Overflow questions之一的回答。
这是一个问题,为了使这段代码对我来说更容易,我创建了一个文件,其中记录了一些调试数据,但是当我创建第二个 fork()时,我的新孩子似乎什么都不记录。我检查存在的进程列表。我不知道为什么它没有将任何内容打印到我的文件中。有任何想法吗? 0.o
我调整后的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#define LOG_FILE "/local_pv/asiwek/daemon_test/daemon_log.log"
static void skeleton_daemon(FILE* file)
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
fprintf(file,"I'm a child! \n");
/* On success: The child process becomes session leader */
if (setsid() < 0)
{
fprintf(file,"ERROR: setsid()! \n");
exit(EXIT_FAILURE);
}
/* Catch,ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD,SIG_IGN);
signal(SIGHUP,SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
{
fprintf(file,"ERROR: fork()! \n");
exit(EXIT_FAILURE);
}
/* Success: Let the parent terminate */
if (pid > 0)
{
fprintf(file,"I'm a parent of the child! pid : %d",pid);
exit(EXIT_SUCCESS);
}
fprintf(file,"New Child!! \n"); // here program stops logging
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/local_pv/asiwek/daemon_test/");
fprintf(file,"chdir \n");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
//openlog ("firstdaemon",LOG_PID,LOG_DAEMON);
fprintf(file,"skeleton_daemon() end. \n");
}
int main()
{
FILE* f = fopen(LOG_FILE,"w");
skeleton_daemon(f);
fprintf(f,"Oh boy I am a daemon!!! \n");
while (1)
{
//TODO: Insert daemon code here.
// syslog (LOG_NOTICE,"First daemon started.");
fprintf(f,"Some log.");
sleep (200);
break;
}
//syslog (LOG_NOTICE,"First daemon terminated.");
//closelog();
fclose(f);
return EXIT_SUCCESS;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。