Linux 如何获取在bash脚本中执行的命令的进程ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21532233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:56:51  来源:igfitidea点击:

How to get the process id of command executed in bash script?

linuxbashshellshsystemd

提问by Skilo Skilo

I have a script i want to run 2 programs at the same time, One is a c program and the other is cpulimit, I want to start the C program in the background first with "&" and then get the PID of the C program and hand it to cpulimit which will also run in the background with "&".

我有一个脚本,我想同时运行 2 个程序,一个是 ac 程序,另一个是 cpulimit,我想先用“&”在后台启动 C 程序,然后获取 C 程序的 PID 和将它交给 cpulimit,它也将在后台运行“&”。

I tried doing this below and it just starts the first program and never starts cpulimit.

我尝试在下面执行此操作,它仅启动第一个程序,而从不启动 cpulimit。

Also i am running this as a startup script as root using systemd in arch linux.

此外,我在 arch linux 中使用 systemd 以 root 身份将其作为启动脚本运行。

#!/bin/bash

/myprogram &

PID=$!

cpulimit -z -p $PID -l 75 &

exit 0

回答by Skilo Skilo

I think i have this solved now, According to this here: linkI need to wrap the commands like this (command) to create a sub shell.

我想我现在已经解决了,根据这里:链接我需要包装这样的命令(命令)来创建一个子shell。

#!/bin/bash

(mygprgram &)
mypid=$!
(cpulimit -z -p $mypid -l 75 &)

exit 0

回答by chris137

I just found this while googling and wanted to add something.

我只是在谷歌搜索时发现了这个并想添加一些东西。

While your solution seems to be working (see comments about subshells), in this case you don't need to get the pid at all. Just run the command like this:

虽然您的解决方案似乎有效(请参阅关于子外壳的评论),但在这种情况下,您根本不需要获取 pid。只需像这样运行命令:

cpulimit -z -l 75 myprogram &