Click here to Skip to main content
15,884,388 members

Comments by Sean Cundiff (Top 2 by date)

Sean Cundiff 24-Mar-24 19:58pm View    
I did some testing and setting PID to 0 in the first argument [sched_setaffinity(0, sizeof(mask), &mask)] does force both the child and parent to run on the same core (in your code).

You can test this in your code by adding the following to your switch statements:

45     case 0: {
46         printf("CHILD CORE:%d:",sched_getcpu());

65     default: {
66         printf("PARENT CORE:%d:",sched_getcpu());


If you comment out your sched_setaffinity block you'll see that they will run on different cores.


So you can, in fact, use 0 --or-- getpid() in your code to lock to the same core.

Your example appears correct for the end of chapter task.
Sean Cundiff 24-Mar-24 19:18pm View    
I see that in the man page. However, there is a program example where they are clearly using getpid() in both the child and parent sections of the switch statement:

switch (fork()) {
           case -1:            /* Error */
               err(EXIT_FAILURE, "fork");

           case 0:             /* Child */
               CPU_SET(childCPU, &set);

               if (sched_setaffinity(getpid(), sizeof(set), &set) == -1)
                   err(EXIT_FAILURE, "sched_setaffinity");

               for (unsigned int j = 0; j < nloops; j++)
                   getppid();

               exit(EXIT_SUCCESS);

           default:            /* Parent */
               CPU_SET(parentCPU, &set);

               if (sched_setaffinity(getpid(), sizeof(set), &set) == -1)
                   err(EXIT_FAILURE, "sched_setaffinity");

               for (unsigned int j = 0; j < nloops; j++)
                   getppid();

               wait(NULL);     /* Wait for child to terminate */
               exit(EXIT_SUCCESS);
           }