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

Skilo Skilo picture Skilo Skilo · Feb 3, 2014 · Viewed 34.8k times · Source

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

Answer

Skilo Skilo picture Skilo Skilo · Feb 3, 2014

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