From 65966ded0cc15c5966c6568cf0ff2f2bbe1fc29a Mon Sep 17 00:00:00 2001 From: Stefan Zabka Date: Sun, 24 May 2020 12:09:46 +0200 Subject: Big remodelling --- shell/beispiele/dup/dup.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 shell/beispiele/dup/dup.c (limited to 'shell/beispiele/dup/dup.c') diff --git a/shell/beispiele/dup/dup.c b/shell/beispiele/dup/dup.c new file mode 100644 index 0000000..ea3c5a6 --- /dev/null +++ b/shell/beispiele/dup/dup.c @@ -0,0 +1,51 @@ +#include +#include +#include + +/* 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; +} -- cgit v1.2.3-54-g00ecf