Advertisement
Guest User

Untitled

a guest
May 30th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <stdlib.h>
  8.  
  9. void process_child(const char *command, char *parameters[])
  10. {
  11. execvp(command, parameters);
  12. }
  13.  
  14.  
  15. char raw_commands[256][256];
  16. char commands[256][256];
  17. char *parameters[256][256];
  18. int n_commands;
  19.  
  20. int main(int argc, char **argv)
  21. {
  22. if (argc != 2) {
  23. printf("Usage: main \"cmd1 cmd_params.. | cmd2 cmd_params... \"");
  24. return 0;
  25. }
  26.  
  27. int i, j, h, k;
  28. for (i=0; i<256; i++) {
  29. for (j=0; j<256; j++) {
  30. parameters[i][j]=(char*)malloc(256*sizeof(char));
  31. }
  32. }
  33. i=0; j=0; h=0; k=0;
  34. int size=strlen(argv[1]);
  35. while (i<size) {
  36. if ((argv[1][i]==' ') && (j==0)) {
  37. j=1;
  38. h=0;
  39. }
  40. else if ((argv[1][i]==' ') && (j==1)) {
  41. k++;
  42. h=0;
  43. }
  44. else if (argv[1][i]=='|') {
  45. n_commands++;
  46. j=0;
  47. h=0;
  48. k=0;
  49. }
  50. else if (j==0) {
  51. commands[n_commands][h]=argv[1][i];
  52. h++;
  53. }
  54. else {
  55. parameters [n_commands][k][h]=argv[1][i];
  56. h++;
  57. }
  58. i++;
  59. }
  60.  
  61.  
  62. int fd_pipe[2]; // 0 -- input, 1 -- output
  63. for (i = 0; i < n_commands; ++i) {
  64. pipe(fd_pipe);
  65.  
  66. int code = fork();
  67. if (!code) {
  68. // child
  69.  
  70. // if last command
  71. if (i + 1 == n_commands) {
  72. close(fd_pipe[1]);
  73. } else {
  74. dup2(fd_pipe[1], 1); // output to created pipe
  75. }
  76.  
  77. close(fd_pipe[0]);
  78.  
  79. process_child(commands[i], parameters[i]);
  80. return 0;
  81. } else {
  82. // parent
  83.  
  84. if (i + 1 == n_commands) {
  85. // last command
  86. close(fd_pipe[0]);
  87. } else {
  88. dup2(fd_pipe[0], 0); // receive input from pipe
  89. }
  90. close(fd_pipe[1]);
  91. }
  92. }
  93.  
  94. for (i = 0; i < n_commands; ++i) {
  95. wait(NULL);
  96. }
  97.  
  98. return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement