编写一程序,要求运行后成为守护进程,复制守护进程的子进程,子进程往某个文件(如test.txt)里写入字符串“测试守护进程:当前系统时间”。父进程等待子进程终止后向系统日志文件“/var/log/messages”写入“子进程终止:当前系统时间”结束,守护进程的错误信息输出到系统日志文件。请把产生守护进程的部分分割成独立的程序文件。提示使用openlog函数和syslog,closelog函数。
时间: 2024-01-22 22:18:31 浏览: 60
这里提供一个守护进程的示例代码,可以参考实现:
daemon.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <syslog.h>
#include <time.h>
void daemonize() {
pid_t pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
if (setsid() < 0) {
exit(EXIT_FAILURE);
}
umask(0);
chdir("/");
int fd = open("/dev/null", O_RDWR);
if (fd < 0) {
exit(EXIT_FAILURE);
}
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
}
int main() {
daemonize();
openlog("daemon-test", LOG_PID, LOG_DAEMON);
pid_t pid = fork();
if (pid < 0) {
syslog(LOG_ERR, "fork error");
exit(EXIT_FAILURE);
}
if (pid == 0) {
int fd = open("test.txt", O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
if (fd < 0) {
syslog(LOG_ERR, "open file error");
exit(EXIT_FAILURE);
}
time_t t;
while (1) {
t = time(NULL);
char *msg = asctime(localtime(&t));
if (write(fd, msg, strlen(msg)) < 0) {
syslog(LOG_ERR, "write file error");
exit(EXIT_FAILURE);
}
sleep(1);
}
} else {
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
syslog(LOG_INFO, "child process terminated normally");
} else if (WIFSIGNALED(status)) {
syslog(LOG_INFO, "child process terminated by signal");
} else {
syslog(LOG_INFO, "child process terminated abnormally");
}
}
closelog();
return 0;
}
```
编译命令:
```
gcc daemon.c -o daemon
```
运行命令:
```
./daemon
```
运行后,程序会成为守护进程,创建子进程并复制它,子进程会不断向文件test.txt写入当前时间戳,父进程会等待子进程终止后向系统日志文件/var/log/messages写入相应信息。程序的错误信息输出到系统日志文件中。
阅读全文