Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. enum { FD_PIPE = 2 };
  6. void stop(int *z, int n){
  7. int i;
  8. for(i = 0; i <= n; i++){
  9. kill(z[i], SIGKILL);
  10. }
  11. while(wait(NULL) > 0) {};
  12. free(z);
  13. exit(1);
  14. }
  15. int
  16. main(int argc, char **argv)
  17. {
  18. int fd[FD_PIPE], i;
  19. int *z = malloc(sizeof(int) * argc);
  20. if(!z){
  21. exit(1);
  22. }
  23. for (i = 1; i < argc - 1; i++) {
  24. if(pipe(fd) < 0){
  25. i--;
  26. stop(z, i - 1);
  27. }
  28. if (!(z[i-1] = fork())) {
  29. close(fd[0]);
  30. dup2(fd[1], 1);
  31. close(fd[1]);
  32. execlp(argv[i], argv[i], NULL);
  33. _exit(1);
  34. } else if(z[i-1] > 0){
  35. if(close(fd[1])){
  36. stop(z, i - 1);
  37. }
  38. if(dup2(fd[0], 0) < 0){
  39. close(fd[0]);
  40. stop(z, i - 1);
  41. }
  42. if(close(fd[0])){
  43. stop(z, i - 1);
  44. }
  45. } else{
  46. if(close(fd[0])){
  47. stop(z, i - 1);
  48. }
  49. if(close(fd[1])){
  50. stop(z, i - 1);
  51. }
  52. i--;
  53. stop(z, i - 1);
  54. }
  55. }
  56. if(argc > 1){
  57. argc--;
  58. if (!(z[argc - 1] = fork())) {
  59. execlp(argv[argc], argv[argc], NULL);
  60. _exit(1);
  61. } else if(z[argc - 1] > 0){
  62. if(close(0)){
  63. stop(z, argc - 1);
  64. }
  65. while(wait(NULL) > 0) {};
  66. free(z);
  67. return 0;
  68. } else{
  69. stop(z, argc - 1);
  70. }
  71. } else{
  72. while(wait(NULL) > 0) {};
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement