将 bash 脚本作为守护进程运行 [英] Run bash script as daemon

查看:21
本文介绍了将 bash 脚本作为守护进程运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,每 X 次运行我的 PHP 脚本:

I have a script, which runs my PHP script each X times:

#!/bin/bash
while true; do
/usr/bin/php -f ./my-script.php
echo "Waiting..."
sleep 3
done

如何将它作为守护进程启动?

How can I start it as daemon?

推荐答案

要在 shell 中将其作为完整的守护进程运行,您需要使用 setsid 并重定向其输出.您可以将输出重定向到日志文件,或重定向到 /dev/null 以丢弃它.假设您的脚本名为 myscript.sh,请使用以下命令:

To run it as a full daemon from a shell, you'll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null &

这会将进程与您当前的 shell(stdin、stdout 和 stderr)完全分离.如果要将输出保存在日志文件中,请将第一个 /dev/null 替换为/path/to/logfile.

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

你必须重定向输出,否则它不会作为一个真正的守护进程运行(它将取决于你的 shell 来读取和写入输出).

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

这篇关于将 bash 脚本作为守护进程运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆