initial import
[staff/goc4/2018bti7061.git] / c-6-additional / examples / c-paralelism / fork2.c
1 /* Source
2 http://www.thegeekstuff.com/2012/05/c-fork-function/
3 */
4
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <errno.h>
8 #include <stdio.h>
9 #include <sys/wait.h>
10 #include <stdlib.h>
11
12 #define MAXLOOP 10
13 #define LOOP 100000000
14
15 int var_glb; /* A global variable*/
16
17 int main(void)
18 {
19 pid_t childPID;
20
21 int i,j,k;
22
23 childPID = fork();
24
25 if(childPID >= 0) // fork was successful
26 {
27 if(childPID == 0) // child process
28 {
29
30 for(i=0;i<MAXLOOP;i++){
31 for(j=0;j<LOOP;j++){
32 k+=1;
33 }
34 printf("Child Process : %d \n",i);
35 }
36
37 }
38 else //Parent process
39 {
40
41 for(i=0;i<MAXLOOP;i++){
42 for(j=0;j<LOOP;j++){
43 k+=1;
44
45 }
46 printf("Parent Process : %d\n",i);
47 }
48
49 }
50 }
51 else // fork failed
52 {
53 printf("\n Fork failed, quitting!!!!!!\n");
54 return 1;
55 }
56
57 return 0;
58 }
59 /* Output:
60 bie1@bie1-VirtualBox:~/svn/examples/cAdditional/parallelism$ ./fork1
61
62 Child Process : 0
63 Parent Process : 0
64 Parent Process : 1
65 Child Process : 1
66 Child Process : 2
67 Child Process : 3
68 Parent Process : 2
69 Parent Process : 3
70 Child Process : 4
71 Parent Process : 4
72 Parent Process : 5
73 Parent Process : 6
74 Child Process : 5
75 Child Process : 6
76 Child Process : 7
77 Parent Process : 7
78 Parent Process : 8
79 Child Process : 8
80 Parent Process : 9
81 Child Process : 9
82 */