diff options
-rw-r--r-- | parallel_progs_by_args.c | 28 |
1 files changed, 22 insertions, 6 deletions
diff --git a/parallel_progs_by_args.c b/parallel_progs_by_args.c index 97505ab..71d09b2 100644 --- a/parallel_progs_by_args.c +++ b/parallel_progs_by_args.c @@ -24,9 +24,10 @@ static void fill_in_item(char *arg, int pid, struct item **list) *list = tmp_item; } -static void make_new_fork(char **begin_pos, struct item **list, +static void make_new_fork(int fd[2], char **begin_pos, struct item **list, int *process_counter) { + static int first_process_flag = 0; int pid = fork(); if(pid == -1) { perror("fork error"); @@ -35,12 +36,23 @@ static void make_new_fork(char **begin_pos, struct item **list, if(pid) { fill_in_item(*begin_pos, pid, list); ++*process_counter; - } - else { + } else { + /* first process writes to pipeline */ + if(first_process_flag == 0) { + close(fd[0]); + dup2(fd[1], 1); + close(fd[1]); + /* second process reads */ + } else { + close(fd[1]); + dup2(fd[0], 0); + close(fd[0]); + } execvp(*begin_pos, begin_pos); perror(*begin_pos); exit(1); } + ++first_process_flag; } static char* find_name_by_pid(int pid, struct item *list) @@ -65,10 +77,12 @@ static void clear_list(struct item *list) int main(int argc, char **argv) { + int fd[2]; int status, pid, process_counter; + char **begin_pos, **end_pos; struct item *list = NULL; process_counter = 0; - char **begin_pos, **end_pos; + pipe(fd); if(argc == 1) { fprintf(stderr, "too few arguments\n"); return 1; @@ -77,13 +91,15 @@ int main(int argc, char **argv) for(begin_pos = argv, end_pos = begin_pos + 1; *end_pos != NULL; ) { if(check_delimiter(*end_pos)) { *end_pos = NULL; - make_new_fork(begin_pos, &list, &process_counter); + make_new_fork(fd, begin_pos, &list, &process_counter); begin_pos = end_pos + 1; end_pos = begin_pos + 1; } else ++end_pos; } - make_new_fork(begin_pos, &list, &process_counter); + make_new_fork(fd, begin_pos, &list, &process_counter); + close(fd[0]); + close(fd[1]); for( ; process_counter; --process_counter) { pid = wait(&status); if(WIFEXITED(status) && WEXITSTATUS(status) == 0) |