Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <errno.h>
  8. #include <ctype.h>
  9.  
  10. int MyExit(int ret)
  11. {
  12. printf("\n");
  13. return ret;
  14. }
  15.  
  16. int main(int argc, char** argv)
  17. {
  18. if(argc != 2)
  19. {
  20. printf("Za dużo/mało argumentów (%d)", argc - 1);
  21. return MyExit(1);
  22. }
  23.  
  24. char* arg = argv[1];
  25. int length = strlen(arg);
  26.  
  27. if(length > 20)
  28. {
  29. printf("Za dużo znaków (%d)", length);
  30. return MyExit(1);
  31. }
  32.  
  33. if (length == 1)
  34. {
  35. //printf("%c", arg[0]);
  36. return arg[0];
  37. }
  38.  
  39. //printf("%s \n", arg);
  40.  
  41. char* firstHalf = (char*)malloc(sizeof(char) * (length/2 + 1));
  42. char* secondHalf = (char*)malloc(sizeof(char) * (length - length/2 + 1));
  43.  
  44. int i;
  45.  
  46. memcpy(firstHalf, arg, length/2);
  47. memcpy(secondHalf, (arg + length/2), length - length/2);
  48. firstHalf[length/2] = '\0';
  49. secondHalf[length - length/2] = '\0';
  50.  
  51. //printf("%s \n", firstHalf);
  52. //printf("%s \n", secondHalf);
  53.  
  54.  
  55. char** childArgs1 = malloc(sizeof(char*)*3);
  56. char** childArgs2 = malloc(sizeof(char*)*3);
  57. int wait1, wait2, ret1, ret2;
  58.  
  59.  
  60. pid_t pid_t1, pid_t2;
  61.  
  62. pid_t1 = fork();
  63.  
  64. if (pid_t1 == 0)
  65. {
  66. childArgs1[0] = "a.out";
  67. childArgs1[1] = firstHalf;
  68. childArgs1[2] = NULL;
  69. execv("a.out", childArgs1);
  70. }
  71.  
  72. pid_t2 = fork();
  73.  
  74. if(pid_t2 == 0)
  75. {
  76. childArgs2[0] = "a.out";
  77. childArgs2[1] = secondHalf;
  78. childArgs2[2] = NULL;
  79. execv("a.out", childArgs2);
  80. }
  81.  
  82. pid_t waitresult1 = waitpid(pid_t1, &wait1, 0);
  83. ret1 = WEXITSTATUS(wait1);
  84. printf("%d %d %s %d \n", getpid(), waitresult1, firstHalf, ret1);
  85.  
  86. pid_t waitresult2 = waitpid(pid_t2, &wait2, 0);
  87. ret2 = WEXITSTATUS(wait2);
  88. printf("%d %d %s %d \n", getpid(), waitresult2, secondHalf, ret2);
  89.  
  90.  
  91. free(firstHalf);
  92. free(secondHalf);
  93. free(childArgs1);
  94. free(childArgs2);
  95.  
  96. if(ret1 > ret2)
  97. return ret1;
  98. else
  99. return ret2;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement