diff options
author | Stefan Zabka <zabkaste@hu-berlin.de> | 2020-05-13 12:16:35 +0200 |
---|---|---|
committer | Stefan Zabka <zabkaste@hu-berlin.de> | 2020-05-13 12:16:35 +0200 |
commit | 00dff9b1d9c3a20ce4b091e092d38f913479a5ac (patch) | |
tree | 4bc5a1af07c4e96d4354ce13a6a7fc62633a6b12 /02_exercise/beispiele/dup/dup.c | |
parent | a2ecab285195ff72fc2955b74f48751ab998809b (diff) | |
download | betriebssysteme-00dff9b1d9c3a20ce4b091e092d38f913479a5ac.tar.gz betriebssysteme-00dff9b1d9c3a20ce4b091e092d38f913479a5ac.zip |
Added all given material for exercise 2
Diffstat (limited to '02_exercise/beispiele/dup/dup.c')
-rw-r--r-- | 02_exercise/beispiele/dup/dup.c | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/02_exercise/beispiele/dup/dup.c b/02_exercise/beispiele/dup/dup.c new file mode 100644 index 0000000..ea3c5a6 --- /dev/null +++ b/02_exercise/beispiele/dup/dup.c @@ -0,0 +1,51 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +/* https://www.youtube.com/watch?v=gaXigSu72A4 */ +static inline void die(const char* msg) { + perror(msg); + exit(EXIT_FAILURE); +} + +int main(int argc, char **argv) { + int pdes[2]; + pid_t child; + + if (pipe(pdes) < 0) + die("pipe()"); + + if ((child = fork()) < 0) + die("fork()"); + + if (child == 0) { + /* child process */ + close(pdes[0]); + close(1); /* close stdout */ + + if (dup(pdes[1]) < 0) + die("dup()"); + + /* now stdout and pdes[1] are equivalent (dup returns lowest free descriptor) */ + if (execlp("cat", "cat", "/etc/passwd", NULL) < 0) + die("execlp()"); + + exit(EXIT_SUCCESS); + } + else { + /* parent process */ + close(0); /* close stdin */ + close(pdes[1]); + + if (dup(pdes[0]) < 0) + die("dup()"); + + /* now stdin and pdes[0] are equivalent (dup returns lowest free descriptor) */ + if (execlp("wc", "wc", "-l", NULL) < 0) + die("execlp()"); + + exit(EXIT_SUCCESS); + } + + return 0; +} |