-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab5_question1.c
78 lines (60 loc) · 1.43 KB
/
lab5_question1.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
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#define MAX_CHILD 5
int main(){
int fd[MAX_CHILD][2];
int v=100,i,which;
int total=0;
int Chile_process=0;
char buffer[256];
int mypipe[MAX_CHILD];
pid_t pid[MAX_CHILD];
char parent_buffer[256];
for(i=0;i<MAX_CHILD;i++){
mypipe[i]=pipe(fd[i]);
pid[i]=fork();
//which=i;
if(pid[i]==0){
Chile_process=1;
break;
}
}
while(Chile_process==1)
{
close(fd[i][0]);
srand(time(NULL)+getpid());
int myrandnum= rand()%10+1;
printf("in child and i is %d and myrandnum is %d\n",i,myrandnum);
sprintf(buffer,"%d", myrandnum);
printf("%s\n",buffer);
write(fd[i][1],buffer,255);
printf("pass write\n");
sleep(myrandnum);
}
while(Chile_process==0){
//close(fd[i][1]);
for(int k=0;k<MAX_CHILD;k++){
close(fd[i][1]);
if(read(fd[k][0],buffer,255)>0)
{
total+=atoi(buffer);
printf("the total is %d \n", total);
sleep(1);
}
}
if (total>30)
{
printf("now total is %d\n", total);
kill(0, SIGKILL);
printf("process is killed\n");
//sleep(1);
}
}
return 0;
}