- View Code
- #include <cstring>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <signal.h>
- #include <iostream>
- #include <fstream>
- #include <cstdlib>
- using namespace std;
- const int MAXFILE = 65535;
- volatile sig_atomic_t _running = 1;
- void sig_handler(int arg)
- {
- _running = 0;
- }
- int main()
- {
- pid_t pid;
- int fd, len;
- char *buf = "This is a Dameon\\n";
- len = strlen(buf);
- pid = fork();
- if (pid < 0)
- {
- cerr << "fork error!" << endl;
- exit(1);
- }
- else if (pid > 0)
- {
- exit(0); //父进程中,则退出
- }
- //以下为在子进程中操作
- cout << getpid() << endl;
- setsid();
- chdir("/home/edward/altraman/tmp");
- umask(0);
- for (int i = 0; i < MAXFILE; i++)
- {
- close(i);
- }
- signal(SIGTERM, sig_handler);
- while(_running)
- {
- ofstream file_rw("/home/edward/altraman/tmp/demon.log", ios::out | ios::app);
- if (!file_rw)
- {
- cerr << "open file failed" << endl;
- exit(1);
- }
- file_rw.write(buf, len);
- file_rw.close();
- usleep(10 * 1000); //10毫秒
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/040320148854.html
来源: http://www.codesnippet.cn/detail/040320148854.html