-
Notifications
You must be signed in to change notification settings - Fork 0
/
potok.cc
103 lines (87 loc) · 2.37 KB
/
potok.cc
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
/* -------------------------------------------------------
program "potok"
-------------------------------------------------------
wywolanie : potok prog1 prog2 prog3 ...
program ten tworzy procesy potomne z podanymi programami
i laczy je "w potok" (dziala jak "prog1|prog2|prog3")
sposob uzycia :
potok ls cat sort sort
potok cat cat sort sort
PYTANIA:
-> co by sie stalo gdyby zostawic lacza otwarte ?
(odpowiedz na to pytanie jest b. istotna !)
-> jaki warunek musza spelniac argumenty
programu "potok" (filtry) ?
*/
#include "unix.h"
struct Lacze {int do_czytania, do_pisania;};
Lacze L[10];
int IloscProg;
void ZamknijLacza()
{
for(int i=0;i<IloscProg-1;i++)
{ close(L[i].do_czytania);
close(L[i].do_pisania);
}
}
// potok prog1 prog2 prog3
// argv: 0 1 2 3
//
main(int argc, char **argv)
{
int i,j;
IloscProg=argc-1;
// tworzenie lacz ...
//
for(i=0;i<IloscProg-1;i++)
{
//pipe((int*)&L[i]);
socketpair(AF_UNIX,SOCK_STREAM,0,(int*)&L[i]);
}
// tworzenie procesow potomnych
// oraz laczenie laczami ...
//
for(i=0;i<IloscProg;i++)
{
int pid;
pid=fork();
if(pid==0) // proces potomny
{
if(i==0) // pierwszy proces (przeadresowujemy tylko stdout)
{
dup2(L[i].do_pisania,1);
ZamknijLacza();
execlp(argv[i+1],argv[i+1],NULL);
fprintf(stderr,"Blad exec (pid==%i) !!!\n",getpid());
exit(1);
}
if(i!=0 && i!=IloscProg-1) // przeadresowujemy stdin i stdout
{
dup2(L[i].do_pisania,1);
dup2(L[i-1].do_czytania,0);
ZamknijLacza();
execlp(argv[i+1],argv[i+1],NULL);
fprintf(stderr,"Blad exec (pid==%i) !!!\n",getpid());
exit(1);
}
if(i==IloscProg-1) // ostatni proces (przeadresowujemy tylko stdin)
{
dup2(L[i-1].do_czytania,0);
ZamknijLacza();
execlp(argv[i+1],argv[i+1],NULL);
fprintf(stderr,"Blad exec (pid==%i) !!!\n",getpid());
exit(1);
}
}
}
// proces macierzysty zamyka wszystkie lacza ...
ZamknijLacza();
// czekamy na wszystkie procesy potomne ...
//
for(i=0;i<IloscProg;i++)
{
int pid,status;
pid=wait(&status);
fprintf(stderr,"wait; pid=%i status=%04X\n",pid,status);
}
}