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/fork_example | |
parent | a2ecab285195ff72fc2955b74f48751ab998809b (diff) | |
download | betriebssysteme-00dff9b1d9c3a20ce4b091e092d38f913479a5ac.tar.gz betriebssysteme-00dff9b1d9c3a20ce4b091e092d38f913479a5ac.zip |
Added all given material for exercise 2
Diffstat (limited to '02_exercise/beispiele/fork_example')
-rw-r--r-- | 02_exercise/beispiele/fork_example/Makefile | 18 | ||||
-rw-r--r-- | 02_exercise/beispiele/fork_example/fork.c | 36 |
2 files changed, 54 insertions, 0 deletions
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 <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/wait.h> + +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; +} |