Search code examples
bashshelltaskaffinity

Commutative property of the commands


I need to ask this question just to double check the answer.

Does the order of the commands matter? For example:

Is this command

 taskset 0x2 time echo "foo"

equal than

time taskset 0x2 echo "foo"

?

I need to know if all the commands followed by the taskset will have the same CPU affinity or just the command immediately after it.


Solution

  • I need to know if all the commands followed by the taskset will have the same CPU affinity or just the command immediately after it.

    Here is a little experiment:

    Start two BG tasks

    $ > taskset 0x2 sleep 50 & sleep 60 &
    

    Get their PIDs

    $ > ps
      PID TTY          TIME CMD
    18562 pts/81   00:00:00 bash
    20750 pts/81   00:00:00 sleep
    20751 pts/81   00:00:00 sleep
    20752 pts/81   00:00:00 ps
    

    Get the CPU affinity of the known PIDs:

    $ > taskset -p 20750
    pid 20750's current affinity mask: 2
    $ > taskset -p 20751
    pid 20751's current affinity mask: 3f
    

    So, it seems like the CPU affinity is set for the first process only.


    Update (trying to explain the following behavior):

    1. /usr/bin/time taskset 0x2 sleep 100000=> only sleep gets the affinity mask 2 (somewhat expected!)
    2. taskset 0x2 /usr/bin/time sleep 100000 => both time and sleep get the affinity mask 2 (need to clarify!)

    In the second case, let's call ps -f to get the PPID (parent PID) for each process:

    $> taskset 0x2 /usr/bin/time sleep 60 &
    [1] 5942
    $> ps -f
    UID        PID  PPID  C STIME TTY          TIME CMD
    user      5942  9698  0 18:19 pts/261  00:00:00 /usr/bin/time sleep 60
    user      5943  5942  0 18:19 pts/261  00:00:00 sleep 60
    user      5944  9698  0 18:19 pts/261  00:00:00 ps -f
    user      9509  9508  0 16:19 pts/261  00:00:00 -bash
    user      9698  9509  0 16:20 pts/261  00:00:00 bash
    $> taskset -p 5942
    pid 5942's current affinity mask: 2
    $> taskset -p 5943
    pid 5943's current affinity mask: 2
    

    What can be seen is that sleep's PPID (5942) corresponds to /usr/bin/time's PID (5942). IOW sleep is a child process of (has been forked from) /usr/bin/time. Because any child process inherits the configuration of the parent process, sleep will have the same CPU affinity with /usr/bin/time.