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