学习日志(十九)
守护进程应用(结合语音控制刷抖音)
将守护进程添加开机自启动
指令:
sudo vi /etc/rc.loacl
写入:守护进程程序所在路径
然后:
sudo reboot
开机后可以看到/home/orangepi/hardware下面有个daemon.log文件记录了日期时间,不需要手动去执行./shouhu
编写判断某程序是否在执行的小脚本
上代码:
1 #include <stdio.h>
2 #include <string.h>
3
4 int main()
5 {
6
7 FILE *file;
8 char buffer[128] = {'\0'};
9
10 char *cmd = "ps -ef|grep douyinPro|grep -v grep";
11 file = popen(cmd,"r");
12
13 fgets(buffer,128,file);
14
15 if(strstr(buffer,"douyinPro")!=NULL){
16
17 printf("douyinPro is running\n");
18 }else{
19 printf("douyinPro is quit\n");
20
21 }
22
23
24 return 0 ;
25 }
测试:
与之前的语音控制刷抖音项目整合
整体框架:
主程序创建一个守护进程,守护进程一直在判断douyinPro是否在运行,不在运行就启动douyinPro,另外创建了信号,信号处理函数一旦检测到SIGQUIT信号,守护进程就退出了
代码部分
1 #include <stdio.h>
2 #include <stdbool.h>
3 #include <time.h>
4 #include <string.h>
5 #include <signal.h>
6 #include <fcntl.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 static bool flag = true;
11
12 void handler(int signum)
13 {
14
15 printf("i get a signal is %d\n",signum);
16 flag = false;
17 }
18
19
20
21 int judge()
22 {
23
24 FILE *file;
25 char buffer[128] = {'\0'};
26
27 char *cmd = "ps -ef|grep douyinPro|grep -v grep";
28 file = popen(cmd,"r");
29 fgets(buffer,128,file);
30
31 if(strstr(buffer,"douyinPro")!=NULL){
32 return 1;
33 }else{
34 return 0;
35 }
36
37 }
38
39 int main()
40 {
41
42 int fd;
43 time_t t;
44
45 if(daemon(0,0)==-1){
46 printf("creat daemon fail\n");
47 exit(-1);
48 }
49 struct sigaction act;
50 act.sa_handler =handler;
51 sigemptyset(&act.sa_mask);
52 act.sa_flags = 0;
53 sigaction(SIGQUIT,&act,NULL);
54
55
56 while(flag ==true){
57 if(judge()==0){
58 system("/home/orangepi/hardware/shuadouyin/douyinPro /dev/ttyS5 &");
59 }
60 sleep(1);
61 }
62
63 return 0 ;
64 }
手动测试:
①
②
最后用上面讲的方法,将守护进程添加开机自启动
顺便刷抖音的程序也加入吧
刷抖音程序的路径在:
/home/orangepi/hardware/shuadouyin/douyinPro
注意写在rc.local里面的形式:
/home/orangepi/hardware/shuadouyin/douyinPro /etc/ttyS5 &
守护进程的程序的路径在:
/home/orangepi/hardware/shuadouyin/shouhuDouyin
命令:
sudo vi /etc/rc.local
写入:
注意:
手机usb调试要手动连接,并且确认调试。