diff options
author | scratko <m@scratko.xyz> | 2024-06-08 01:44:31 +0300 |
---|---|---|
committer | scratko <m@scratko.xyz> | 2024-06-08 01:44:31 +0300 |
commit | 42191da2512b6f48f7ccd7765a416a7bc9aeeca6 (patch) | |
tree | 6d8ac9a387cb8b4740c55174801542b10df5f255 | |
parent | 23df85221e08fe5dc1f0eb6df3c48f299f243895 (diff) | |
download | parallel-progs-by-args-42191da2512b6f48f7ccd7765a416a7bc9aeeca6.tar.gz parallel-progs-by-args-42191da2512b6f48f7ccd7765a416a7bc9aeeca6.tar.bz2 parallel-progs-by-args-42191da2512b6f48f7ccd7765a416a7bc9aeeca6.zip |
Added unidirectional data channel for process communication (pipe).
-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) |