Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 217
Skilo Skilo Avatar asked Feb 03 '14 16:02

Skilo Skilo


People also ask

How do I find the process ID of a running script in Unix?

A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system. The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

What is process ID in shell script?

As a child process of the main shell, a subshell executes a list of commands in a shell script as a batch (so-called "batch processing"). In some cases, you may want to know the process ID (PID) of the subshell where your shell script is running. This PID information can be used under different circumstances.

How do I display the process ID PID of the current shell?

$ expands to the process ID of the shell. So, you can see the PID of the current shell with echo $$ . See the Special Paramaters section of man bash for more details.


2 Answers

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
like image 171
Skilo Skilo Avatar answered Nov 08 '22 15:11

Skilo Skilo


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 &
like image 45
chris137 Avatar answered Nov 08 '22 13:11

chris137