1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <fcntl.h>
4
+ #include <unistd.h>
5
+ #include <sys/wait.h> // For wait, waitpid
6
+
7
+ #define PORTNUM 1500 // Port > 1024 because program will not work not as root.
8
+ #define NUMBER_OF_PROCESSES 2
9
+ #define EXIT_FAILURE 1
10
+
11
+ // Compilation:
12
+ // gcc -std=gnu99 "00 - Processes.c" -o processes
13
+
14
+ // Task:
15
+ // Use fork to create a child process.
16
+
17
+ void main (int argc , char * argv [])
18
+ {
19
+ printf ("0 Enter to main!\n" );
20
+ for (int i = 0 ; i < NUMBER_OF_PROCESSES ; i ++ )
21
+ {
22
+ pid_t pid ;
23
+ int status ;
24
+ switch (pid = fork ())
25
+ {
26
+ case -1 :
27
+ perror ("1 Error of calling fork" );
28
+ exit (EXIT_FAILURE );
29
+ case 0 :
30
+ printf ("1 CHILD: Child process %d!\n" , getpid ());
31
+ printf ("2 CHILD: Parent PID %d!\n" , getppid ());
32
+ printf ("3 CHILD: Wait 10 seconds...\n" );
33
+ sleep (10 );
34
+ printf ("4 CHILD: Exit!\n" );
35
+ exit (EXIT_FAILURE );
36
+ default :
37
+ printf ("1 PARENT: Parent process %d!\n" , getpid ());
38
+ printf ("2 PARENT: Child PID %d\n" , pid );
39
+ printf ("3 PARENT: Wait until child calls exit()...\n" );
40
+ waitpid (pid , & status , 0 );
41
+ printf ("4 PARENT: Child exit code: %d\n" , WEXITSTATUS (status ));
42
+ printf ("5 PARENT: Exit!\n" );
43
+ }
44
+ }
45
+
46
+ printf ("1 Exit main!\n" );
47
+ exit (0 );
48
+ }
0 commit comments