fork download
  1. #include <stdio.h>
  2. #include <sys/wait.h>
  3. #include <unistd.h>
  4. #include<stdlib.h>
  5.  
  6. void childProcess(int ar[], int n){
  7. for(int i = 0; i < n; i++){
  8. for(int j = 0; j < n - 1 - i; j++){
  9. if(ar[j] > ar[j+1]){
  10. int temp = ar[i];
  11. ar[i] = ar[j];
  12. ar[j] = temp;
  13. }
  14. }
  15. }
  16. }
  17.  
  18. void parentProcess(int ar[], int n){
  19. for(int i = 0; i < n; i++){
  20. int j = i;
  21. while(j > 0 && ar[j - 1] > ar[j]){
  22. int temp = ar[i];
  23. ar[i] = ar[j];
  24. ar[j] = temp;
  25. j--;
  26. }
  27. }
  28. }
  29.  
  30.  
  31. int main(){
  32. int n;
  33.  
  34. printf("Enter the number of elements: ");
  35. scanf("%d", &n);
  36.  
  37. int ar[100];
  38. printf("Enter the Numbers: \n");
  39. for(int i = 0; i < n; i++) scanf("%d", &ar[i]);
  40.  
  41. int p;
  42. p = fork();
  43. if(p == -1){
  44. printf("Error while creating a child\n");
  45. }else if(p == 0){
  46. printf("We are in the child process to sort the array (Bubble Sort)\n");
  47. printf("Child Process ID: %d\n", getpid());
  48. printf("Parent Process ID: %d\n", getppid());
  49. childProcess(ar, n);
  50.  
  51. printf("After Sort in Child: \n");
  52. for (int i = 0; i < n; i++){
  53. printf(" %d ", ar[i]);
  54. }
  55. printf("\n");
  56. }else{
  57. wait(3000);
  58. printf("We are in the parent process (Insertion sort)\n");
  59. printf("Parent => PID: %d\n", getpid());
  60. parentProcess(ar, n);
  61. printf("After Sort in Parent: \n");
  62. for (int i = 0; i < n; i++){
  63. printf(" %d ", ar[i]);
  64. }
  65. printf("\n");
  66. }
  67. }
  68.  
  69.  
Success #stdin #stdout 0.01s 5284KB
stdin
3
4
5
6
stdout
Enter the number of elements: Enter the Numbers: 
We are in the child process to sort the array (Bubble Sort)
Child Process ID: 1725304
Parent Process ID: 1725301
After Sort in Child: 
 4  5  6 
Enter the number of elements: Enter the Numbers: 
We are in the parent process (Insertion sort)
Parent => PID: 1725301
After Sort in Parent: 
 4  5  6