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?

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. Commented Aug 29, 2019 at 12:08
  • 1
    Possible duplicate of How do I set a variable to the output of a command in Bash? Commented Aug 29, 2019 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) Commented Aug 29, 2019 at 12:24

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.