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?

Shubhamizm
  • 35
  • 3
  • 1
    Do you start each process from the bash script? If so use `$!` just after creation, it refers to the PID of the last job started in background. – Aaron Aug 29 '19 at 12:08
  • 1
    Possible duplicate of [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – Biffen Aug 29 '19 at 12:12
  • Rather than using `pidof` (which will possibly get the process id's of unrelated processes), you may prefer to use `jobs -p` (which also may grab pids you don't want. Pick your poison). `chrt -f -p 1 $(jobs -p)` – William Pursell Aug 29 '19 at 12:24

2 Answers2

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 
Fazlin
  • 2,285
  • 17
  • 29
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.

chepner
  • 497,756
  • 71
  • 530
  • 681