SHARE
TWEET

Untitled

a guest Aug 18th, 2017 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <unistd.h>
  2. #include <stdio.h>
  3.  
  4. typedef void* list_item;
  5. typedef int(list_item) worker_func
  6.  
  7. int process_list(list_item* list_item_array, unsigned int length,
  8.                  worker_func async_func, worker_func sync_func)
  9. /* Beware: recursive fork ;)
  10.    Dispatches async_func on last item of array in parallel with forked
  11.    process doing same for (n-1)-th item of array;
  12.    then waits for child process to finish and dispatches the sync_func
  13.    Performance is fine: most shells limit the number of cmd args
  14. */
  15. {
  16.     pid_t pid = 0;
  17.     if (length > 1) {
  18.         // fork, baby, fork
  19.         pid = fork();
  20.         if (pid < 0)
  21.             printf("Fork failed -- ABANDON SHIP\n");
  22.         else if (pid == 0) // child process
  23.             return process_list(list_item_array, length-1,
  24.                                 async_func, sync_func);
  25.     }
  26.     // actually do some stuff
  27.     async_func(list_item_array[length-1]);
  28.     if (pid) // wait for child to finish to execute sync_funcs synchronously
  29.         waitpid(pid);
  30.     sync_func(list_item_array[length-1]);
  31.    
  32.     return 0;
  33. }
RAW Paste Data
Top