diff options
author | Stefan Zabka <zabkaste@hu-berlin.de> | 2020-05-24 12:09:46 +0200 |
---|---|---|
committer | Stefan Zabka <zabkaste@hu-berlin.de> | 2020-05-24 12:09:46 +0200 |
commit | 65966ded0cc15c5966c6568cf0ff2f2bbe1fc29a (patch) | |
tree | 60af69be16926ef0f24ad2a954d9205ce9277450 /shell/beispiele/pipe_example | |
parent | 3b7e61eab8ce5d230bc1b172942c1ab9459ed161 (diff) | |
download | betriebssysteme-65966ded0cc15c5966c6568cf0ff2f2bbe1fc29a.tar.gz betriebssysteme-65966ded0cc15c5966c6568cf0ff2f2bbe1fc29a.zip |
Big remodelling
Diffstat (limited to 'shell/beispiele/pipe_example')
-rw-r--r-- | shell/beispiele/pipe_example/Makefile | 18 | ||||
-rw-r--r-- | shell/beispiele/pipe_example/pipe.c | 60 |
2 files changed, 78 insertions, 0 deletions
diff --git a/shell/beispiele/pipe_example/Makefile b/shell/beispiele/pipe_example/Makefile new file mode 100644 index 0000000..d69473e --- /dev/null +++ b/shell/beispiele/pipe_example/Makefile @@ -0,0 +1,18 @@ +#!/usr/bin/make +.SUFFIXES: + +CFLAGS = -c -Os -Wall -Werror + +%.o: %.c + $(CC) $(CFLAGS) $^ -o $@ + +%: %.o + $(CC) -o $@ $^ + +all: pipe + +run: all + ./pipe + +clean: + $(RM) $(RMFILES) pipe diff --git a/shell/beispiele/pipe_example/pipe.c b/shell/beispiele/pipe_example/pipe.c new file mode 100644 index 0000000..422e4d5 --- /dev/null +++ b/shell/beispiele/pipe_example/pipe.c @@ -0,0 +1,60 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#define BUF_SIZE 32 + +int pipe_fds[2]; + +void term(const char *msg) { + if (msg) { + fprintf(stderr, "Error: %s\n", msg); + fflush(stderr); + } + + int close_fail = 0; + int ret = close(pipe_fds[0]); + + if (ret < 0) { + fprintf(stderr, "Error: Couldn't close reading end of pipe\n"); + fflush(stderr); + close_fail = 1; + } + + ret = close(pipe_fds[1]); + + if (ret < 0) { + fprintf(stderr, "Error: Couldn't close writing end of pipe\n"); + fflush(stderr); + close_fail = 1; + } + + exit((msg || close_fail) ? EXIT_FAILURE : EXIT_SUCCESS); +} + +int main(void) { + int ret = pipe(pipe_fds); + + if (ret < 0) + term("Couldn't create pipe"); + + char out_buf[] = "hello"; + ret = write(pipe_fds[1], out_buf, strlen(out_buf) + 1); + + if (ret < 0) + term("Couldn't write to pipe"); + + printf("send msg: %s\n", out_buf); + + char in_buf[BUF_SIZE]; + memset(in_buf, 0, BUF_SIZE); + + ret = read(pipe_fds[0], in_buf, BUF_SIZE - 1); + + if (ret < 0) + term("Couldn't read from pipe"); + + printf("recv msg: %s\n", in_buf); + return 0; +} |