summaryrefslogtreecommitdiffstats
path: root/shell/beispiele/dup
diff options
context:
space:
mode:
Diffstat (limited to 'shell/beispiele/dup')
-rw-r--r--shell/beispiele/dup/Makefile18
-rw-r--r--shell/beispiele/dup/dup.c51
2 files changed, 69 insertions, 0 deletions
diff --git a/shell/beispiele/dup/Makefile b/shell/beispiele/dup/Makefile
new file mode 100644
index 0000000..0f73ac4
--- /dev/null
+++ b/shell/beispiele/dup/Makefile
@@ -0,0 +1,18 @@
+#!/usr/bin/make
+.SUFFIXES:
+
+CFLAGS = -c -Os -Wall -Werror
+
+%.o: %.c
+ $(CC) $(CFLAGS) $^ -o $@
+
+%: %.o
+ $(CC) -o $@ $^
+
+all: dup
+
+run: all
+ ./dup
+
+clean:
+ $(RM) $(RMFILES) dup
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 <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;
+}