守护进程开发方式
直接借助damon()函数完成。
##include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdbool.h>
//C 库函数 char *asctime(const struct tm *timeptr) 返回一个指向字符串的指针,它代表了结构 struct timeptr 的>日期和时间。
//C 库函数 struct tm *localtime(const time_t *timer) 使用 timer 的值来填充 tm 结构。timer 的值被分解为 tm 结
构,并用本地时区表示。
/*
struct tm {
int tm_sec; 秒,范围从 0 到 59
int tm_min; 分,范围从 0 到 59
int tm_hour; 小时,范围从 0 到 23
int tm_mday; 一月中的第几天,范围从 1 到 31
int tm_mon; 月份,范围从 0 到 11
int tm_year; 自 1900 起的年数
int tm_wday; 一周中的第几天,范围从 0 到 6
int tm_yday; 一年中的第几天,范围从 0 到 365
int tm_isdst; 夏令时
};
*/
static bool flag = true;
void handler(int sig)
{
printf("I got a signal %d\nI'm quitting.\n", sig);
flag = false;
}
int main()
{
time_t t;
int fd;
//创建守护进程
if(-1 == daemon(0, 0))
{
printf("daemon error\n");
exit(1);
}
//设置信号处理函数
struct sigaction act;
act.sa_handler = handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if(sigaction(SIGQUIT, &act, NULL))
{
printf("sigaction error.\n");
exit(0);
}
//进程工作内容
while(flag)
{
fd = open("/home/orangepi/daemon.log", O_WRONLY | O_CREAT | O_APPEND,0644);
if(fd == -1)
{
printf("open error\n");
}
t = time(0);
char *buf = asctime(localtime(&t));
write(fd, buf, strlen(buf));
close(fd);
sleep(10);
}
return 0;
}
守护进程应用
需求:要求语音刷手机的程序一直保持运行,防止应用程序崩溃意外
编写判断某进程是否在运行的程序:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *file;
char buffer[128] = {'\0'};
char *cmd = "ps -elf |grep douyin|grep -v grep";
file = popen(cmd, "r");
fgets(buffer, 128, file);
if(strstr(buffer, "douyin") != NULL){
printf("douyinPro is running\n");
}else{
printf("douyinPro is not running\n");
}
printf("BUFFER:%s\n",buffer);
}
守护进程不让控制程序退出
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdbool.h>
static bool flag = true;
void handler(int sig)
{
printf("I got a signal %d\nI'm quitting.\n", sig);
flag = false;
}
int judMent()
{
FILE *file;
char buffer[128] = {'\0'};
char *cmd = "ps -elf |grep douyinUtils|grep -v grep";
file = popen(cmd, "r");
fgets(buffer, 128, file);
if(strstr(buffer, "douyinUtils") != NULL){
return 0;
}else{
return -1;
}
printf("BUFFER:%s\n",buffer);
}
int main()
{
time_t t;
int fd;
//创建守护进程
if(-1 == daemon(0, 0))
{
printf("daemon error\n");
exit(1);
}
//设置信号处理函数
struct sigaction act;
act.sa_handler = handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if(sigaction(SIGQUIT, &act, NULL))
{
printf("sigaction error.\n");
exit(0);
}
//进程工作内容
while(flag)
{
if( judMent() == -1){
system("/home/orangepi/hardwareSoft/douyin/douyinUtils /dev/ttyS5 &");
}
sleep(2);
}
return 0;
}
想要开机自启动有一种简单的方法使用 sudo vi /etc/rc.local 添加,绝对路径加程序名字
守护进程和后台进程的区别
- 守护进程和终端不挂钩;后台进程能往终端上输出东西(和终端挂钩);
- 守护进程关闭终端时不受影响,守护进程不会随着终端的退出而退出;