I have a script (.sh) where I launch applications like this

./application1 configuration1.cfg  param1 param2 param3 &

sleep 2

./application2 configuration2.cfg  param1 param2 param3 &

sleep 2


Is there a way that I can assign the CPU affinity as I launch the process?

I don't really want to do it after the fact. I could do it programatically from C++, but it seems that the shell is the best way to do it.

Then, once launched, how do I verify that it is indeed stuck to that CPU/core?


There is a utility, taskset, part of util-linux, for just this purpose. For example:

taskset -c 0-15 script

will run script and constrain it to use just CPUs with IDs 0 to 15.

To check that your scripts are indeed constrained to run on the proper CPUs, you can look at the file /proc/<pid>/status: it will have entries named Cpus_allowed (a bitmap; the least significant bit is set if CPU 0 is allowed) and Cpus_allowed_list (a list of CPU IDs).

  • Hmmm, strange, when I add taskset to run the script from the command line, or I add taskset in front of each program that I am starting inside the script, my program behaves completely differently and wrong. – Ivan Mar 31 '15 at 14:41
  • If you can describe the issue in more detail, that could be material for a separate question. – dhag Mar 31 '15 at 14:46

I'm mid "learning experience" myself, but this might be relevant.

To run a bash script in the background on a specific cpu, try:

taskset -c 1 ./myScript &

In myScript include the lines:

echo MyScript: $$\($BASHPID\) taskset -cp $BASHPID

$BASHPID, which is new to me, is: "The process ID of the current Bash process. In some cases, this can differ from $$."

Personally I'm struggling to run a bash function in the background on a specific cpu.

taskset -c 1 ./myFunction &

... gave me: taskset: failed to execute myFunction: No such file or directory

While after some false starts

(taskset -cp 1 $BASHPID;myFunction)&

... looks promising.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.