程序(nload)在shell中执行时作为守护进程运行,但不在启动/自动化脚本中执行

Program (nload) runs as a daemon when executed in shell but not in startup/automation script

本文关键字:执行 运行 启动 脚本 自动化 进程 nload shell 程序 守护      更新时间:2023-10-16

我想在启动时作为守护进程运行nload(一种网络吞吐量监视器)(或者通常只是自动化)。我可以从命令行成功地将其作为守护程序运行,方法是键入以下内容:

nload eth0 >& /dev/null &

只是一些背景:我稍微修改了nload源代码(用C++编写),除了输出到屏幕之外,还可以写入文件。我想从nload写入的文件中读取吞吐量值。我输出到/dev/null的原因是为了不必担心stdout输出。

奇怪的是,当我手动运行它时,它运行得很好,而且我可以从文件中读取吞吐量值。但每一次自动化尝试都失败了。我尝试过init.d、rc.local、cron,但没有成功。我写的在自动化中运行这个脚本是:

#!/bin/bash
echo "starting nload"
/usr/bin/nload eth0 >& /dev/null &
if [ $? -eq 0 ]; then
    echo started nload
else
    echo failed to start nload
fi

我可以确认,当自动化时,脚本确实会运行,因为我尝试记录输出。它甚至记录"已启动nload",但当我查看运行nload的进程列表时,它并不是其中之一。我还可以确认,当脚本从shell手动运行时,nload作为守护进程启动得很好。

有人知道在通过自动脚本运行时,是什么阻止了这个程序的运行吗?

如果nload不是从终端运行,它看起来就像是崩溃了。

viroos@null-linux:~$ cat /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
strace -o /tmp/nload.trace /usr/bin/nload
exit 0

看起来缺少HOME env var:

viroos@null-linux:~$ cat /tmp/nload.trace
brk(0x1f83000)                          = 0x1f83000
write(2, "Could not retrieve home director"..., 34) = 34
write(2, "n", 1)                       = 1
exit_group(1)                           = ?
+++ exited with 1 +++

让我们解决这个问题:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
export HOME=/tmp
strace -o /tmp/nload.trace /usr/bin/nload
exit 0

我们还有一个问题:

viroos@null-linux:~$ cat /tmp/nload.trace
read(3, "321367120210unknown|unknown term"..., 4096) = 320
read(3, "", 4096)                       = 0
close(3)                                = 0
munmap(0x7f23e62c9000, 4096)            = 0
ioctl(2, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, 0x7ffedd149010) = -1 ENOTTY (Inappropriate ioctl for device)
ioctl(2, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, 0x7ffedd148fb0) = -1 ENOTTY (Inappropriate ioctl for device)
write(2, "Error opening terminal: unknown."..., 33) = 33
exit_group(1)                           = ?
+++ exited with 1 +++

我看到你提到你修改了nload代码,但我猜你还没有删除处理丢失的term。您可以尝试进一步编辑nload代码或在分离模式下使用屏幕:

viroos@null-linux:~$ cat /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
export HOME=/tmp
screen -S nload -dm /usr/bin/nload

exit 0