diff --git a/lab2/solution_2.c b/lab2/solution_2.c new file mode 100644 index 0000000..2cea102 --- /dev/null +++ b/lab2/solution_2.c @@ -0,0 +1,73 @@ +/* + * This code is identical to running + * cat $1 | sort | uniq + * in bash + */ +#include +#include + + +void run_cat(char* filename, int pfd[2]) { + dup2(pfd[1], STDOUT_FILENO); + close(pfd[0]); + close(pfd[1]); + + char cmd[] = "/usr/bin/cat"; + char *args[] = {"cat", filename, NULL}; + execve(cmd, args, NULL); +} + +void run_sort(int pfd1[2], int pfd2[2]) { + dup2(pfd1[0], STDIN_FILENO); + dup2(pfd2[1], STDOUT_FILENO); + close(pfd1[0]); + close(pfd1[1]); + close(pfd2[0]); + close(pfd2[1]); + + char cmd[] = "/usr/bin/sort"; + char *args[] = {"sort", NULL}; + execve(cmd, args, NULL); +} + +void run_uniq(int pfd[2]) { + dup2(pfd[0], STDIN_FILENO); + close(pfd[0]); + close(pfd[1]); + + char cmd[] = "/usr/bin/uniq"; + char *args[] = {"uniq", NULL}; + execve(cmd, args, NULL); +} + +void check_args(int argc, char** argv) { + if (argc != 2) { + printf("Usage: %s \n", argv[0]); + _exit(1); + } +} + +int main(int argc, char** argv) { + int pfd1[2]; + pipe(pfd1); + + int pid = fork(); + + if (pid == 0) { + run_cat(argv[1], pfd1); + } else { + close(pfd1[1]); + + int pfd2[2]; + pipe(pfd2); + + int pid2 = fork(); + + if (pid2 == 0) { + run_sort(pfd1, pfd2); + } else { + close(pfd1[0]); + run_uniq(pfd2); + } + } +}