Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <unistd.h>
  5.  
  6. void childsWork(int ID);
  7.  
  8. int main(int argc, char **argv) {
  9. int numOfChildProcesses;
  10.  
  11. // Receive an integer numeric command line argument representing the number
  12. // of child processes to create represented by numOfChildProcesses
  13. char c;
  14. if(sscanf(argv[1], "%d %c", &numOfChildProcesses, &c) != 1) {
  15. printf("Must include integer numeric command line argument");
  16. return -1;
  17. }
  18.  
  19. // Create a number of child processes equal to numOfChildProcesses
  20. for(int i = 0; i < numOfChildProcesses; i++) {
  21. int pid = fork();
  22. // Determine whether current process is a child process (i.e. PID = 0)
  23. // If true, execute childs work and exit gracefully
  24. // If false, continue
  25. if(pid == 0) {
  26. childsWork(i);
  27. exit(0);
  28. }
  29. }
  30.  
  31. return 0;
  32. }
  33.  
  34. void childsWork(int ID) {
  35. // Arbitrarily simulate a variable amount of time that a processes
  36. // task could take to complete
  37. srand(time(NULL));
  38. int n = rand() % 10000000;
  39. for(int i = 0; i < n; i++);
  40. printf("Child: %d, PID: %d\n", ID, getpid());
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement