设计了两种退出方式:exit和NULL崩溃。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
void sleep_second(int seconds)
{
usleep(seconds*1000*1000);
}
#define NULL_EXCEPTION
#define LOG_FILE "/home/weiyu/service.log"
int main(int argc, char** argv)
{
int count = 0;
while (1)
{
int fd = open(LOG_FILE, O_RDWR|O_APPEND|O_CREAT, 0666);
char data[128] = {0};
count ++;
sprintf(data, "count=%d\n", count);
write(fd, data, strlen(data));
if (count == 3)
{
#ifdef NULL_EXCEPTION
sprintf(data, "count=3, NULL error and restart to 1\n");
#else
sprintf(data, "count=3, exit(0) and restart to 1\n");
#endif
write(fd, data, strlen(data));
}
close(fd);
if (count == 3)
{
#ifdef NULL_EXCEPTION
char* pError = NULL;
sprintf(pError, "EXCEPTION\n");
#else
exit(0);
#endif
}
sleep_second(5);
}
return 0;
}
gcc test.cpp -o worker
[Unit]
Description=巍宇航天科技
After=systemd-user-sessions.service
[Service]
Type=simple
ExecStart=/home/weiyu/worker
KillSignal=SIGQUIT
# 重启模式是无论怎样都会重启这个程序,无法用 kill -9 杀死
Restart=always
# 这个表示重启的信号,也反过来映射的只有使用 systemctl stop 程序名,才能停止此程序
RestartPreventExitStatus=1 6 SIGABRT
$ cp weiyu.service /etc/systemd/system
$ systemctl stop weiyu.service
$ systemctl start weiyu.service