Skip to content

Instantly share code, notes, and snippets.

@stephen-hannam
Created May 30, 2022 23:42
Show Gist options
  • Save stephen-hannam/7d2e8d8a657086de0d85a27fd07f69f0 to your computer and use it in GitHub Desktop.
Save stephen-hannam/7d2e8d8a657086de0d85a27fd07f69f0 to your computer and use it in GitHub Desktop.
C - fork and pin to cpu

Template: Recursive Calls if fork returns positive value

#include <sched.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                        } while (0)
                        
cpu_set_t set;
CPU_ZERO(&set);

int fork_func(<args>)
{
  uint32_t pid = 0;
  ...
  switch(fork())
  {
      case -1:
          errExit("fork");

      case 0:
          CPU_SET(<cpu#>, &set);

          pid = getpid();

          if (sched_setaffinity(pid, sizeof(set), &set) == -1)
              errExit("sched_setaffinity");

          if (do_func(<args>) == -1)
              return -1;
          break;

      default:
          if (fork_func(<args>) == -1)
              return -1;
          break;
  }
  ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment