-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminishell.cpp
119 lines (95 loc) · 2.09 KB
/
minishell.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
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<dirent.h>
#include<stdlib.h>
#include<sys/types.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<fstream>
#include <sys/wait.h>
#include <sstream>
#include<fcntl.h>
using namespace std;
void take_input();
void prin_side()
{
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("%s:~$",buf);
take_input();
}
void parse(string str)
{
stringstream ss(str);
vector<string>v;
string sp;
while(getline(ss,sp,'|'))
{
v.push_back(sp);
}
int p[2];
pid_t pid;
int fd_in = 0;
int ind=0;
while(ind<v.size())
{
pipe(p);
pid=fork();
if (pid == 0)
{
dup2(fd_in, 0); //change the input according to the old one
if ((ind + 1) != v.size())
dup2(p[1], 1);
else
{
int pos=v[ind].find(">");
if(pos!=-1)
{
int len=v[ind].length();
string comm=v[ind].substr(0,pos);
v[ind]=v[ind].substr(pos+1,len-pos-1);
int fdout=open(v[ind].c_str(),O_WRONLY|O_CREAT);
v[ind]=comm;
int df=dup2(fdout,1);
}
}
close(p[0]);
//execvp((*cmd)[0], *cmd);
char* arg[5];
for(int i=0;i<5;i++)
arg[i]=NULL;
int cnt=0;
stringstream st(v[ind]);
string div[5];
while(getline(st,div[cnt],' '))
{
arg[cnt]=const_cast<char*>(div[cnt].c_str());
cnt++;
}
execvp(arg[0],arg);
exit(EXIT_FAILURE);
}
else
{
wait(NULL);
close(p[1]);
fd_in = p[0]; //save the input for the next command
ind++;
}
}
}
void take_input()
{
string input_command;
getline(cin,input_command);
parse(input_command);
}
int main()
{
prin_side();
return 0;
}