linuxubuntuexectaskset

how to allocate processor to exec process


I can allocate a cpu core to a process, by running it like this:

taskset -c 21 ./wait xx

Here, ./wait is an executable, whose code is shown below, and I am trying to assign the core=21 to this process.

But when I try to do the same from another process (using execl), it does not work. Eg, the following code executes the process (no errors reported), but the core allocation to that process is not done:

// run as: ./a.out name 21
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>

int main(int argc, char* argv[]) {
    printf("scheduling\n");
    int status = execl("/usr/bin/taskset", "-c", argv[2], "./wait", argv[1], NULL);
    if(status<0) perror("Err:");
}

Here is the code for the wait program, it just waits for user to give some input, so that I get time to check the cpu status from another terminal:

// run as: ./wait name
#include <stdio.h>
#include <stdarg.h>

int main(int argc, char* argv[]) {
    printf("%s:asking for user input\n", argv[1]);
    int x;
    scanf("%d", &x);
    printf("got-%d\n", x);
}

So, my question is: how to allocate the cpu-core using execl when running a process? (BTW, if the process is already running and I have its pid, then exec of taskset on that pid will change that process's core allocation. It does not work only when it is done in the way shown here.)


Solution

  • You need to supply the process name to be argv[0] in the child:

    int status = execl("/usr/bin/taskset",
                       "taskset", "-c", argv[2], "./wait", argv[1], NULL);
    

    With the name missing, the program is invoked as -c 21 ./wait xx instead of taskset -c 21 ./wait xx that we intended, meaning that it won't see the -c as argument, and will instead interpret 21 as a mask (processors 0 and 5) rather than a list (processor 21 only).