-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab5_question2.c
111 lines (86 loc) · 1.94 KB
/
lab5_question2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#define MAXCHILD 5
#define MAXIMUM 100
int main(){
pid_t child [MAXCHILD];
int child_process=0;
int fd [2];
char path[20];
int pipe;
int i;
int goal_val=MAXCHILD-1;
int max=MAXCHILD;
int status=0;
sprintf(path,"1.pipe");
mkfifo(path,0777);
char buffer[256];
bzero(buffer,256);
for (i=0;i<MAXCHILD;i++){
child[i]=fork();
if(child[i]==0){
child_process=1;
break;
}
}
if (child_process==1)
{
printf("child %d starts\n", i);
pipe=open(path,O_RDWR);
while (1){
read(pipe,buffer,255);
goal_val=atoi(buffer);
printf("child %d pipe pipevalue is: %d\n",i, goal_val );
if (goal_val==-1)
{
int zero=-1;
sprintf(buffer,"%d", zero);
write(pipe,buffer,strlen(buffer));
printf("child %d reach the point\n", i);
exit(0);
}
else
{
if (goal_val==i)
{
goal_val--;
sprintf(buffer,"%d", goal_val);
write(pipe,buffer,strlen(buffer));
}
else
{
sprintf(buffer,"%d", goal_val);
write(pipe,buffer,strlen(buffer));
}
}
sleep(1);
}
}
if (child_process==0)
{
pipe=open(path,O_WRONLY);
char buff[256];
sprintf(buff,"%d", max-1);
write(pipe,buff,strlen(buff));
while(1){
for (int i=0; i<MAXCHILD; i++)
{
int childd=wait(&status);
if (childd==-1)
{
printf("finished\n");
exit(0);
}
}
sleep(1);
}
return 0;
}
}