【问题标题】:How to return the PID from a bash script executed from a bash script如何从 bash 脚本执行的 bash 脚本返回 PID
【发布时间】:2018-07-02 22:57:59
【问题描述】:

下面的get_pid() 函数旨在返回daemon_itinerary.sh 的PID。

下面的脚本与daemon_itinerary.sh不在同一个工作目录中。

#!/bin/bash

PID=""

get_pid() {
    PID='pidof daemon_itinerary.sh'
}

start() {
    echo "Restarting test_daemon"
    get_pid
    if [[ -z $PID ]]; then
        echo "starting test_daemon .."
        sh /var/www/bin/daemon_itinerary.sh &
        get_pid
        echo "done. PID=$PID"
    else
        echo "test_deamon is alrady running, PID=$PID"
    fi
}

case "$1" in
start)
    start
;;
...
*)
    echo "Usage: $0 {start|stop|restart|status}"
esac

*编辑

Start 作为命令行参数传入。

【问题讨论】:

  • 那么,问题是什么? :-|
  • 你不是从任何地方调用 start() 吗??
  • pidof daemon_itinerary.sh 应该用反引号,而不是单引号。
  • 使 daemon_itinerary.sh 可执行 (700) 并直接调用,而不是使用“sh”。然后使用'pidof -x daemon_itinerary.sh'
  • 并非如此,因为 Roadawl 建议您应该使用 pidof -x daemon_itinerary.sh。要在变量中捕获 PID,它应该是 pid=$(pidof daemon_itinerary.sh)。请注意 pid 变量的小写,因为 PID 是 bash 中的保留名称。

标签: bash ubuntu-16.04 daemon


【解决方案1】:

我们使用 pgrep 来获取进程的 pid,如下所示

PID=$(pgrep -f "daemon_itinerary.sh" | xargs)

# xargs - is given because pgrep will return both process id as well as parent pid
# also it will help us to get all pids if multiple instances are running.
# pgrep option to get session id or parent id alone, here its from manual
# -P, --parent ppid,...
#     Only match processes whose parent process ID is listed.
# -s, --session sid,...
#     Only match processes whose process session ID is listed. Session ID 0 is translated into pgrep's or pkill's own session ID.

【讨论】:

    最近更新 更多