在前台启动进程时,在Shell脚本中获取进程ID

Nag*_*nan 4 linux shell

在shell程序中,我想启动一个程序并获取其PID并保存在临时文件中.但是在这里我将在前台启动程序,并且在进程处于运行状态之前不会退出shell

例如:

 #!/bin/bash

 myprogram &
 echo "$!"  > /tmp/pid
Run Code Online (Sandbox Code Playgroud)

这工作正常,我能够得到启动过程的pid.但如果我在前期启动该程序,我想知道如何获得pid

例如:

#!/bin/bash

myprogram       /// hear some how i wan to know the PID before going to next line
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 11

正如我在上面评论的那样,因为你的命令仍然在前台运行,你不能在同一个shell中输入新命令并转到下一行.

但是,当此命令正在运行并且您希望从不同的shell选项卡/窗口进程获取此程序的进程ID时,请使用pgrep如下所示:

pgrep -f "myprogram"
17113 # this # will be different for you :P
Run Code Online (Sandbox Code Playgroud)

编辑:根据您的评论or is it possible to launch the program in background and get the process ID and then wait the script till that process gets exited ?

是的,可以使用wait pid命令完成,如下所示:

myprogram &
mypid=$!
# do some other stuff and then
wait $mypid
Run Code Online (Sandbox Code Playgroud)