From 04576dc2a3f761eb041b808b56f13a58052e7655 Mon Sep 17 00:00:00 2001 From: Stefan Zabka Date: Sun, 24 May 2020 12:19:52 +0200 Subject: Moved back to 02_exercise --- 02_exercise/beispiele/fork_example/Makefile | 18 +++++++++++++++ 02_exercise/beispiele/fork_example/fork.c | 36 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 02_exercise/beispiele/fork_example/Makefile create mode 100644 02_exercise/beispiele/fork_example/fork.c (limited to '02_exercise/beispiele/fork_example') diff --git a/02_exercise/beispiele/fork_example/Makefile b/02_exercise/beispiele/fork_example/Makefile new file mode 100644 index 0000000..8f69ed9 --- /dev/null +++ b/02_exercise/beispiele/fork_example/Makefile @@ -0,0 +1,18 @@ +#!/usr/bin/make +.SUFFIXES: + +CFLAGS = -c -Os -Wall -Werror + +%.o: %.c + $(CC) $(CFLAGS) $^ -o $@ + +%: %.o + $(CC) -o $@ $^ + +all: fork + +run: all + ./fork + +clean: + $(RM) $(RMFILES) fork diff --git a/02_exercise/beispiele/fork_example/fork.c b/02_exercise/beispiele/fork_example/fork.c new file mode 100644 index 0000000..7377b0f --- /dev/null +++ b/02_exercise/beispiele/fork_example/fork.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +int main(void) { + pid_t proc_id; + int status = 0; + + proc_id = fork(); + + if (proc_id < 0) { + fprintf(stderr, "fork error\n"); + fflush(stderr); + return EXIT_FAILURE; + } + + if (proc_id == 0) { + /* child process */ + printf("[child] process id: %d\n", (int) getpid()); + + char* args[] = {"sleep", "1", NULL}; + execvp(args[0], args); + exit(-1); + } + else { + /* parent */ + printf("[parent] process id: %d\n", (int) getpid()); + pid_t child_id = wait(&status); + + printf("[parent] child %d returned: %d\n", + child_id, WEXITSTATUS(status)); + } + + return EXIT_SUCCESS; +} -- cgit v1.2.3-54-g00ecf