标签:文章 content class 调试 track bin 退出 close blank
那么,如何才干找回这些数据?
2、将标准输入。标准输出,标准错误都重定向/dev/null
daemon 实现大致例如以下:
int daemonize(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return (-1); case 0: break; default: _exit(EXIT_SUCCESS); } if (setsid() == -1) return (-1); if (nochdir == 0) { if(chdir("/") != 0) { perror("chdir"); return (-1); } } if (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1) { if(dup2(fd, STDIN_FILENO) < 0) { perror("dup2 stdin"); return (-1); } if(dup2(fd, STDOUT_FILENO) < 0) { perror("dup2 stdout"); return (-1); } if(dup2(fd, STDERR_FILENO) < 0) { perror("dup2 stderr"); return (-1); } if (fd > STDERR_FILENO) { if(close(fd) < 0) { perror("close"); return (-1); } } } return (0); }
#include <signal.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> static int fd = -1; void sigroutine(int dunno) { switch (dunno) { case SIGUSR1: fprintf(stderr, "Get a signal -- SIGUSR1 \n"); if (fd != -1) close(fd); fd = open("/tmp/console_temp.log", O_RDWR|O_APPEND|O_CREAT, 0600); if (fd == -1) break; dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); break; case SIGUSR2: fprintf(stderr, "Get a signal -- SIGUSR2 \n"); if (fd != -1) close(fd); fd = open("/dev/null", O_RDWR, 0); if (fd == -1) break; dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); break; } return; } int main() { signal(SIGUSR1, sigroutine); signal(SIGUSR2, sigroutine); daemon(1,0); for (;;){ fprintf(stderr,"test \n") ; // 不断打印test sleep(1); } return 0; }
00:00:00 ./daemon_example
如上,进程后台执行了。拿到pid 11328
#!/bin/bash pid=$1 ps -p $pid>/dev/null if [ ! $? -eq 0 ] ; then echo pid does not exist! exit 1 fi echo pid $pid trap "kill -usr2 $pid && exit 1" HUP INT QUIT TERM kill -usr1 $pid echo it works,please wait.. sleep 1 tail -f -n 0 /tmp/console_temp.log echo done!
当然,这仅仅是一个演示样例。实际应用中要做改善。比方kill信号改成pipe或socket通讯,缓存文件要大小限制。或自己主动清除等。
标签:文章 content class 调试 track bin 退出 close blank
原文地址:http://www.cnblogs.com/cxchanpin/p/7255605.html