Bash: 运行后台任务并获取PID

2 投票
1 回答
4379 浏览
提问于 2025-04-18 06:41
$1 &
echo $!

有没有其他方法可以在后台启动一个命令,并立即返回它的进程ID(pid)?

比如,当我运行 bash run.sh "python worker.py" 时,它会给我启动的任务的进程ID。

我正在使用 paramiko,这是一个 Python 库,但它不支持 python worker.py & 这种写法。所以我想创建一个 bash 脚本,让它在远程服务器上为我完成这个任务。

1 个回答

1

因为你在使用bash这个工具,你可以通过输入jobs来查看后台运行的程序列表,并且可以加上-l这个选项来获取每个程序的进程ID(PID)。根据man bash的说明:

   jobs [-lnprs] [ jobspec ... ]
   jobs -x command [ args ... ]
          The first form lists the active jobs.  The options have the
          following meanings:
          -l     List process IDs in addition to the normal information.

所以在你的情况下,像这样输入 jobs -l | grep 'worker.py' | awk '{print $2}' 可能就能得到你想要的结果。

撰写回答