How to store the value returned by a command in shell script?

0

i am new to shell scripts. I have task where i have to create multiple instances of a c program, run them in background and alter their scheduling policy using chrt utility.

In chrt utility i need to give the process IDs for every process to alter it's scheduling policy.

Now i have to add all these in a shell script to automate the process.

My question is, after creating the instances, how do i fetch the process ID of every instance and store it in a variable?

gcc example.c -o w1
taskset 0x00000001 ./w1&
taskset 0x00000001 ./w1&
taskset 0x00000001 ./w1&
taskset 0x00000001 ./w1&

pidof w1

chrt -f -p 1 <pid1>     

pidof w1 will give the process ids of all the instances. Now how do i store all these IDs in variables or array and pass them in chrt command?

linux
bash
shell
asked on Stack Overflow Aug 29, 2019 by Shubhamizm

2 Answers

1

Read this article: https://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

To store the output of command in a variable:

pids=$(pidof w1)

To use the variable:

for each in $pids
do
  # parse each values and pass to chrt command
  chrt -f -p 1 $each
done 
answered on Stack Overflow Aug 29, 2019 by Fazlin
1

You only need pidof because you ignored the process IDs of the background jobs in the first place.

gcc example.c -o w1
pids=()
taskset 0x00000001 ./w1 & pids+=($!)
taskset 0x00000001 ./w1 & pids+=($!)
taskset 0x00000001 ./w1 & pids+=($!)
taskset 0x00000001 ./w1 & pids+=($!)

for pid in "${pids[@]}"; do
  chrt -f -p 1 "$pid"
done

The special parameter $! contains the process ID of the most recently backgrounded process.

answered on Stack Overflow Aug 29, 2019 by chepner

User contributions licensed under CC BY-SA 3.0