-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecute.cpp
55 lines (47 loc) · 1014 Bytes
/
execute.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
#include <sys/wait.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <string>
#include <sstream>
#include <fstream>
#define STDIN 0
#define STDOUT 1
int main(int argc,char* argv[]){
/*
execute ./main main input.txt
*/
// for(int i=0;i< argc;i++)
// std::cout<<i<<" argument: "<<argv[i]<<"\n";;
int p[2];
int ff=open(argv[argc - 1],O_RDONLY);
std::ifstream file(argv[argc -1]);
if ( pipe(p) == -1 ) {
std::cout << "pipe failed" << std::endl;
return 0;
}
pid_t pid= fork();
if(!pid) {
dup2(p[STDIN],0);
close(p[STDOUT]);
if(argc == 4)
execl(argv[1], argv[2],NULL);
else
execl(argv[1], argv[2],argv[3],NULL);
} else {
dup2(ff,0);
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
write(p[STDOUT],file_contents.c_str(),file_contents.size());
// close(p[STDOUT]);
}
int status;
waitpid(pid,&status,0);
return 0;
}