If you set the CPU for the calling process, then it looks like every child process will have the same settings.
For example, given:
When i have a look (in an other terminal) to the status of top instances:
for pid in $(ps aux|grep -i top|grep -v grep|awk '{print $2}') ; do taskset -p ${pid} ; done
pid 2505's current affinity mask: 4
pid 2515's current affinity mask: 4
pid 2525's current affinity mask: 4
Here is an example of bash script that do the job:
#!/bin/bash
echo "Setting CPU affinity ..."
# Bind to a given CPU
taskset -p 4 $$
# Verify it worked
taskset -p $$
echo "Launching background jobs ..."
# Now, launch several background jobs
for i in $(seq 0 10) ; do
tail -f /dev/null &
done
echo "Checking ..."
# Now for each instance of background jobs, check CPU affinity
for pid in $(pidof tail) ; do
taskset -p ${pid}
done
sleep 1
killall tail
And the resulting output:
Setting CPU affinity ...
pid 4313's current affinity mask: f
pid 4313's new affinity mask: 4
pid 4313's current affinity mask: 4
Launching background jobs ...
Checking ...
pid 4327's current affinity mask: 4
pid 4326's current affinity mask: 4
pid 4325's current affinity mask: 4
pid 4324's current affinity mask: 4
pid 4323's current affinity mask: 4
pid 4322's current affinity mask: 4
pid 4321's current affinity mask: 4
pid 4320's current affinity mask: 4
pid 4319's current affinity mask: 4
pid 4318's current affinity mask: 4
./test.sh: line 24: 4317 Terminated tail -f /dev/null
./test.sh: line 24: 4318 Terminated tail -f /dev/null
./test.sh: line 24: 4319 Terminated tail -f /dev/null
./test.sh: line 24: 4320 Terminated tail -f /dev/null
./test.sh: line 24: 4321 Terminated tail -f /dev/null
./test.sh: line 24: 4322 Terminated tail -f /dev/null
./test.sh: line 24: 4323 Terminated tail -f /dev/null
./test.sh: line 24: 4324 Terminated tail -f /dev/null
./test.sh: line 24: 4325 Terminated tail -f /dev/null
./test.sh: line 24: 4326 Terminated tail -f /dev/null
./test.sh: line 24: 4327 Terminated tail -f /dev/null