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

倾然丶 夕夏残阳落幕 提交于 2019-12-10 12:41:51

问题


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 "&".

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

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

#!/bin/bash

/myprogram &

PID=$!

cpulimit -z -p $PID -l 75 &

exit 0

回答1:


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

#!/bin/bash

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

exit 0



回答2:


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:

cpulimit -z -l 75 myprogram &


来源:https://stackoverflow.com/questions/21532233/how-to-get-the-process-id-of-command-executed-in-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!