Introduction
Contents
1. Introduction#
In the first part of this book we will introduce the foundations of our topic.
1.1. Overview#
What a grand adventure we have begun.
1print("hello, world")
2print("hello, world")
3print("hello, world")
4print("hello, world")
Here is the example C code
1#include <sys/types.h>
2#include <unistd.h>
3#include <stdio.h>
4#include <stdlib.h>
5
6int
7main(int argc, char* argv[])
8{
9 pid_t mypid, cpid, ppid;
10 cpid = fork();
11 ppid = getppid();
12 mypid = getpid();
13
14 if (cpid > 0) {
15 /* Parent code */
16 printf("hello, from parent with pid %d, pid of child is %d\n", mypid, cpid);
17 } else if (cpid == 0) {
18 /* Child code */
19 printf("hello, I am child with pid %d, my parent is %d\n", mypid, ppid);
20 } else {
21 perror("fork failed\n");
22 exit(-1);
23 }
24 return 0;
25}
Here is another example C code
1#include <sys/types.h>
2#include <unistd.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <sys/wait.h>
6#include "doforke.h"
7
8
9int
10do_fork_exec(char *prog, char *const argv[])
11{
12 pid_t cpid;
13 int status=0;
14 cpid = fork();
15 if (cpid < 0) {
16 perror("fork failed\n");
17 exit(-1);
18 }
19
20 if (cpid != 0) {
21 // parent code, we need to wait for child
22 waitpid(cpid,&status,0);
23 } else {
24 execve(prog, argv, 0);
25 perror("should never get here\n");
26 }
27 return status;
28}