linux - Implementation of multiple pipelines and command executions in C -


i have homework asks me create shell executes multiple commands separated pipelines. here code snippet forking childs , executing commands:

    (int = 0; < commands; i++) {          place = commandstarts[i];          if((pid = fork()) < 0) exit(1);         else if (pid == 0) {             if(i < pipe_counter && dup2(fds[j + 1], 1) < 0) exit(1);// if not last remaining command              if(j != 0 && dup2(fds[j-2], 0) < 0) exit(1);        // if not first command              for(int c = 0; c < 2*pipe_counter; c++) close(fds[c]);              if(execvp(argv[place], argv+place)) exit(0);        // execute , if returns anything, exit!         }         j+=2;     }      for(int = 0; < 2 * pipe_counter; i++) close(fds[i]);      while ((wait(&status)) != pid);                     // program gets point                                          //     parent process, should wait completion 

even though, seems working fine in simple examples, in more complex, grading system gives me hint: should wait processes in pipe chain terminate before displaying prompt, no last one!

can tell mistake is?

well, mistake was waiting last forked child terminate.

here correct code snippet waits every child terminate:

    (int = 0; < commands; i++) {          place = commandstarts[i];          if((pid = fork()) < 0) exit(1);         else if (pid == 0) {             if(i < pipe_counter && dup2(fds[j + 1], 1) < 0) exit(1);// if not last remaining command              if(j != 0 && dup2(fds[j-2], 0) < 0) exit(1);            // if not first command              for(int c = 0; c < 2*pipe_counter; c++) close(fds[c]);              if(execvp(argv[place], argv+place)) exit(1);            // execute , if returns anything, exit!         }         j+=2;     }      for(int = 0; < 2 * pipe_counter; i++) close(fds[i]);      for(int = 0; < commands; i++) wait(&status);            // program gets point                                                                  //     parent process, should wait completion. 

also many wallyk helping me think through!


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -