summaryrefslogtreecommitdiffstats
path: root/shell/beispiele/fork_example/fork.c
blob: 7377b0f87bb71546315267d0a10581606a8ad4ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;
}