Skip to content

Commit 71e8909

Browse files
committed
feat: 守护进程 setsid()
1 parent af8f676 commit 71e8909

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

unix_linux_16_daemon/mySetsid

8.77 KB
Binary file not shown.

unix_linux_16_daemon/mySetsid.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include <stdio.h>
2+
#include <unistd.h>
3+
#include <sys/wait.h>
4+
#include <sys/time.h>
5+
#include <sys/types.h>
6+
#include <fcntl.h>
7+
#include <signal.h>
8+
#include <sys/stat.h>
9+
#include <time.h>
10+
11+
void func(int no); //用作回调函数,给 signal() 调用
12+
13+
int main(int argc, char *argv[])
14+
{
15+
pid_t pid = fork();
16+
17+
if (pid > 0) {
18+
_exit(1); //父进程退出
19+
} else if (pid == 0) {
20+
setsid(); //子进程创建为会话
21+
chdir("/Users/muli/Desktop/"); //改变进程的工作目录
22+
umask(0); //重设置文件掩码
23+
24+
close(STDIN_FILENO); //关闭和终端的联系,文件描述符
25+
close(STDOUT_FILENO);
26+
close(STDERR_FILENO);
27+
28+
__sigaction_u sigactu; //设置信号捕捉
29+
sigactu.__sa_handler = func;
30+
31+
struct sigaction act;
32+
act.sa_flags = 0;
33+
act.__sigaction_u = sigactu;
34+
sigaddset(&act.sa_mask, SIGQUIT);
35+
36+
itimerval time; //设置周期性的定时器
37+
time.it_value.tv_sec = 2;
38+
time.it_value.tv_usec = 0;
39+
time.it_interval.tv_sec = 1;
40+
time.it_interval.tv_usec = 0;
41+
42+
sigaction(SIGVTALRM, &act, NULL); //捕捉(下面一行发射的)信号,在 fun() 里面实现
43+
setitimer(ITIMER_VIRTUAL, &time, NULL); //使用定时器,发射信号
44+
45+
while (true); //保持该守护进程不死亡
46+
}
47+
48+
return 0;
49+
}
50+
51+
void func(int no)
52+
{
53+
time_t currtime; //获取系统当前时间,传出参数
54+
time(&currtime);
55+
char* ptr = ctime(&currtime);
56+
57+
int fd = open("/Users/muli/Desktop/setsid.txt", O_CREAT | O_WRONLY | O_APPEND, 0777); //写入磁盘文件
58+
write(fd, ptr, sizeof(ptr) + 1);
59+
close(fd);
60+
}

unix_linux_16_daemon/setsid.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1Sat Apr 1

0 commit comments

Comments
 (0)