Skilo Skilo
Skilo Skilo

Reputation: 526

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

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

Upvotes: 16

Views: 37303

Answers (2)

chris137
chris137

Reputation: 189

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 &

Upvotes: 2

Skilo Skilo
Skilo Skilo

Reputation: 526

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

Upvotes: 5

Related Questions