summaryrefslogtreecommitdiffstats
path: root/02_exercise/beispiele/fork_example/fork.c
diff options
context:
space:
mode:
authorStefan Zabka <zabkaste@hu-berlin.de>2020-05-24 12:19:52 +0200
committerStefan Zabka <zabkaste@hu-berlin.de>2020-05-24 12:19:52 +0200
commit04576dc2a3f761eb041b808b56f13a58052e7655 (patch)
treec6bed6db34e29f0dec0c844fbc931b3dd4fab8db /02_exercise/beispiele/fork_example/fork.c
parent65966ded0cc15c5966c6568cf0ff2f2bbe1fc29a (diff)
downloadbetriebssysteme-04576dc2a3f761eb041b808b56f13a58052e7655.tar.gz
betriebssysteme-04576dc2a3f761eb041b808b56f13a58052e7655.zip
Moved back to 02_exercise
Diffstat (limited to '02_exercise/beispiele/fork_example/fork.c')
-rw-r--r--02_exercise/beispiele/fork_example/fork.c36
1 files changed, 36 insertions, 0 deletions
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;
+}