编写一个守护进程实现某些功能。如每10秒将当前时间写入文件,当守护进程收到SIGUSR1信号后退出
时间: 2024-05-03 08:17:40 浏览: 117
以下是一个简单的守护进程实现:
```python
import os
import time
import signal
def write_time_to_file():
with open('time.txt', 'a') as f:
f.write(time.strftime("%Y-%m-%d %H:%M:%S\n"))
def sigusr1_handler(signum, frame):
print('Received SIGUSR1 signal, exiting...')
os._exit(0)
def daemon():
# Fork a child process
pid = os.fork()
if pid != 0:
# Parent process
print('Daemon PID:', pid)
return
# Child process
signal.signal(signal.SIGUSR1, sigusr1_handler)
while True:
write_time_to_file()
time.sleep(10)
if __name__ == '__main__':
daemon()
```
这个守护进程会每10秒将当前时间写入文件time.txt,当收到SIGUSR1信号时会退出。可以在命令行中发送SIGUSR1信号来结束守护进程:
```bash
$ kill -s SIGUSR1 <daemon_pid>
```
阅读全文