Skip to content

Commit dc70128

Browse files
committed
Add example of a child executing another program
1 parent f6a22fd commit dc70128

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

fork_this_shit/Makefile

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22
# Add all targets here
3-
BINARIES=simple_fork child_status
3+
BINARIES=simple_fork child_status child_exec
44

55
all: $(BINARIES)
66

@@ -17,6 +17,12 @@ child_status.o: child_status.c
1717
gcc child_status.c -c
1818

1919

20+
child_exec: child_exec.o
21+
gcc -o child_exec child_exec.o
22+
child_exec.o: child_exec.c
23+
gcc child_exec.c -c
24+
25+
2026
.PHONY: clean
2127
clean:
2228
rm -f *.o $(BINARIES)

fork_this_shit/child_exec.c

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <sys/types.h>
2+
#include <sys/wait.h>
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
#include <unistd.h>
6+
7+
int main(int argc, char *argv[])
8+
{
9+
pid_t pid;
10+
pid = fork();
11+
12+
if (pid < 0) {
13+
/* there was an error */
14+
fprintf(stderr, "%d: Fork failed\n", getpid());
15+
} else if (pid == 0) {
16+
/* child gets a pid of zero */
17+
printf("Child:\n");
18+
execl("/bin/ls", "ls", NULL);
19+
printf("We'll never reach here\n");
20+
} else {
21+
/* inside parent */
22+
wait(NULL);
23+
printf("\nChild complete\n");
24+
}
25+
26+
return 0;
27+
}

0 commit comments

Comments
 (0)