Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- typedef void* list_item;
- typedef int(list_item) worker_func
- int process_list(list_item* list_item_array, unsigned int length,
- worker_func async_func, worker_func sync_func)
- /* Beware: recursive fork ;)
- Dispatches async_func on last item of array in parallel with forked
- process doing same for (n-1)-th item of array;
- then waits for child process to finish and dispatches the sync_func
- Performance is fine: most shells limit the number of cmd args
- */
- {
- pid_t pid = 0;
- if (length > 1) {
- // fork, baby, fork
- pid = fork();
- if (pid < 0)
- printf("Fork failed -- ABANDON SHIP\n");
- else if (pid == 0) // child process
- return process_list(list_item_array, length-1,
- async_func, sync_func);
- }
- // actually do some stuff
- async_func(list_item_array[length-1]);
- if (pid) // wait for child to finish to execute sync_funcs synchronously
- waitpid(pid);
- sync_func(list_item_array[length-1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement