如何将脚本设为守护进程

3

我正在尝试在Ubuntu上使用daemon,但是即使阅读了man页面,我仍然不确定如何使用它。

我有以下测试脚本foo.sh

#!/bin/bash
while true; do
    echo 'hi' >> ~/hihihi
    sleep 10
done

然后我尝试了这个命令,但没有任何反应:

daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- foo.sh

文件hihihi未被更新,我在错误日志中发现了这个问题:

20161221 12:12:36 foo: client (pid 176193) exited with 1 status

我该如何正确使用daemon命令?


看一下 nohup。nohup script .sh & 非常高效和简单。 - NinjaGaiden
我没有访问Ubuntu系统进行测试,但您可以尝试启动一个shell来解释foo.shdaemon ... /bin/sh ~/foo.sh - Serge Ballesta
2个回答

1

在bash中不需要使用daemon命令。你可以手动将你的脚本变成守护进程。例如:

#!/bin/bash

# At first you have to redirect stdout and stderr to /dev/null
exec >/dev/null
exec 2>/dev/null

# Fork and go to background
(
while true; do
    echo 'hi' >> ~/hihihi
    sleep 10
done
)&
# Parent process finished but child still working

1
据我所知,大多数 daemondeamonize 程序在守护进程化过程中会将当前目录更改为根目录。这意味着您必须提供命令的完整路径:
daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- /path/to/foo.sh

如果仍然无法正常工作,您可以尝试指定一个shell:
daemon --name="foo" -b ~/daemon.out -l ~/daemon.err -v -- /bin/bash -c /path/to/foo.sh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接