|
发表于 2024-10-16 10:49:29
|
显示全部楼层
创建一个守护进程需要一些步骤,包括脱离终端、创建新会话、处理信号等。下面是一个简单的示例程序,实现了每秒清理指定目录下的`.txt`文件。
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <dirent.h>
- #include <string.h>
- #include <fcntl.h>
- #include <signal.h>
- void daemonize() {
- pid_t pid;
- // 创建子进程
- pid = fork();
- if (pid < 0) {
- exit(EXIT_FAILURE);
- }
- // 父进程退出
- if (pid > 0) {
- exit(EXIT_SUCCESS);
- }
- // 成为领导进程
- if (setsid() < 0) {
- exit(EXIT_FAILURE);
- }
- // 捕捉信号
- signal(SIGCHLD, SIG_IGN);
- signal(SIGHUP, SIG_IGN);
- // 再次fork,保证不会重新获得终端
- pid = fork();
- if (pid < 0) {
- exit(EXIT_FAILURE);
- }
- if (pid > 0) {
- exit(EXIT_SUCCESS);
- }
- // 修改文件掩码
- umask(0);
- // 改变工作目录
- chdir("/");
- // 关闭文件描述符
- for (int x = sysconf(_SC_OPEN_MAX); x >= 0; x--) {
- close(x);
- }
- }
- void clean_txt_files(const char *directory) {
- struct dirent *entry;
- DIR *dp = opendir(directory);
- if (dp == NULL) {
- perror("opendir");
- return;
- }
- char filepath[1024];
- while ((entry = readdir(dp))) {
- // 检查文件扩展名是否是.txt
- if (strstr(entry->d_name, ".txt") != NULL) {
- snprintf(filepath, sizeof(filepath), "%s/%s", directory, entry->d_name);
- remove(filepath);
- }
- }
- closedir(dp);
- }
- int main() {
- const char *directory = "/path/to/your/directory"; // 修改为你的目录路径
- daemonize();
- while (1) {
- clean_txt_files(directory);
- sleep(1); // 每秒执行一次
- }
- return 0;
- }
复制代码
注意事项:
- 修改`/path/to/your/directory`为你要清理的实际目录路径。
- 确保你的程序有权限删除该目录下的文件。
- 运行该程序时需要以管理权限(如`root`用户)执行,以确保能够正常改变目录和关闭文件描述符。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|