-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipeFDcout.cpp
141 lines (102 loc) · 2.44 KB
/
pipeFDcout.cpp
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
* testFD
* Date: May-04-2022
* Author : Gabriel Renaud gabriel.reno [at sign here ] gmail.com
*
*/
#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int writeNumbers(){
//ofstream oFile;
//cerr<<"writeNumbers "<<filename<<endl;
//oFile.open(filename, ios::out);
cerr<<"opened"<<endl;
// if (oFile.is_open()){
for(int i=1;i<11;i++){
cout<<i<<endl;
cerr<<"writing "<<(i*2)<<endl;
}
//oFile.close();
return 0;
// }else{
// cerr << "Unable to write to file "<<filename<<endl;
// return 1;
// }
}
int rwDoubleNumbers(const string & filenamein,const string & filenameout){
string line;
ifstream iFile;
ofstream oFile;
cerr<<"rwDoubleNumbers "<<filenamein<<" "<<filenameout<<endl;
iFile.open(filenamein.c_str(), ios::in);
oFile.open(filenameout.c_str(), ios::out);
if (!iFile.is_open()){
cerr << "Unable to open file "<<filenamein<<endl;
return 1;
}
if (!oFile.is_open()){
cerr << "Unable to write to file "<<filenameout<<endl;
return 1;
}
while(getline (iFile,line)){
int i=stoi(line);
cerr<<"read "<<i<<" writing "<<(i*2)<<endl;
oFile<<(i*2)<<endl;
}
iFile.close();
oFile.close();
return 0;
}
int main (int argc, char *argv[]) {
char * myfifo = "fifo0";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
pid_t pid1 = fork();
if (pid1 == -1) {
cerr<<"error in fork"<<endl;
exit(1);
}else{
if(pid1 == 0) {
cerr<<"child "<<endl;
pid_t pid2 = fork();
if (pid2 == -1) {
cerr<<"error in fork"<<endl;
exit(1);
}else{
if(pid2 == 0) {
cerr<<"child of child "<<endl;
rwDoubleNumbers(string(myfifo),"double.txt");
exit(0);
}else{
cerr<<"child#1 "<<endl;
//send stdout to fifo
fstream fout;
fout.open(myfifo, ios::out);
streambuf* sbcout = cout.rdbuf();
streambuf* sbfile = fout.rdbuf();
cout.rdbuf(sbfile);
writeNumbers();
cout.rdbuf(sbcout);
fout.close();
pid_t wpid;
int status = 0;
while ((wpid = wait(&status)) > 0);
exit(0);
}
}
}else{
cerr<<"parent "<<endl;
}
}
pid_t wpid;
int status = 0;
while ((wpid = wait(&status)) > 0);
//wait for the
remove(myfifo);
}