fork download
  1. #include<unistd.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<sys/wait.h>
  5. #include<sys/types.h>
  6.  
  7.  
  8. void swap(int *a , int *b)
  9. {
  10. int temp = *a;
  11. *a = *b;
  12. *b = temp;
  13. }
  14. void sort_assending(int arr[] , int n )
  15. {
  16. for(int i = 0 ; i < n - 1 ; i++)
  17. {
  18. for(int j = 0 ; j < n - i - 1 ; j++)
  19. {
  20. if(arr[j] > arr[j + 1])
  21. {
  22. swap(arr + j , arr + j + 1);
  23. }
  24. }
  25. }
  26. }
  27.  
  28. void sort_descending(int arr[] , int n )
  29. {
  30. for(int i = 0 ; i < n - 1 ; i++)
  31. {
  32. for(int j = 0 ; j < n - i - 1 ; j++)
  33. {
  34. if(arr[j] < arr[j + 1])
  35. {
  36. swap(arr + j , arr + j + 1);
  37. }
  38. }
  39. }
  40. }
  41. int main()
  42. {
  43. int n;
  44. printf("Enter number of elements in an array:\n");
  45. scanf("%d" , &n);
  46. int arr[n];
  47. for(int i = 0 ; i < n ; i++)
  48. {
  49. printf("Enter the %dth element : " , i + 1);
  50. scanf("%d" , &arr[i]);
  51. }
  52. pid_t pid;
  53.  
  54. pid = fork();
  55.  
  56. if(pid < 0)
  57. {
  58. printf("Fork failed to create a child process...!\n");
  59. exit(1);
  60. }
  61. else if(pid == 0)
  62. {
  63. // Child process execution start from here as pid = 0
  64. printf("Child process execution starts: sorting in descending order\n");
  65.  
  66. sort_descending(arr , n);
  67.  
  68. for(int i = 0 ; i < n ; i++)
  69. {
  70. printf("\t\t%d Child process : %d , parent id : %d\n" , arr[i] , getpid() , getppid());
  71. // sleep(1);
  72. }
  73. printf("Child execution finished\n");
  74. }
  75. else
  76. {
  77.  
  78. //waiting to start child its execution
  79. sleep(1);
  80. // Parent execution starts from here
  81. printf("Parent execution starts: sorting in assending order\n");
  82.  
  83. sort_assending(arr , n);
  84.  
  85. for(int i = 0 ; i < n ; i++)
  86. {
  87. printf("%d , Parent process id: %d , child id : %d , parent id : %d\n", arr[i] , getpid() , pid , getppid());
  88. sleep(5);
  89. }
  90. // wait(NULL);
  91.  
  92. printf("Parent execution finished\n");
  93. }
  94. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Enter number of elements in an array:
Child process execution starts: sorting in descending order
Child execution finished
Enter number of elements in an array:
Parent execution starts: sorting in assending order
Parent execution finished