linux service 测试
1.创建一个app
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main()
{
FILE *fp;
time_t now;
char buffer[80];
fp = fopen("/tmp/time_log.txt", "w");
if (fp == NULL)
{
perror("Error opening file");
return (-1);
}
while (1)
{
time(&now);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S\n", localtime(&now));
fprintf(fp, "%s", buffer);
fflush(fp);
sleep(10);
}
fclose(fp);
return 0;
}
gcc myapp.c -o myapp
sudo mv myapp /usr/local/bin/
sudo chmod 777 /usr/local/bin/myapp
cd /usr/local/bin
./myapp
tail -n 3 /tmp/time_log.txt
rm /tmp/time_log.txt
2.创建服务
[Unit]
Description=My Application Service
After=network.target
[Service]
Type=simple
User=c
ExecStart=/usr/local/bin/myapp
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo mv myapp.service /etc/systemd/system/
cd /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl start myapp.service
sudo systemctl stop myapp.service
sudo systemctl status myapp.service
sudo systemctl enable myapp.service
sudo systemctl disable myapp.service
journalctl -u myapp.service
tail -n 3 /tmp/time_log.txt
rm /tmp/time_log.txt