This repository was archived by the owner on Mar 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminishell.c
More file actions
110 lines (98 loc) · 1.75 KB
/
minishell.c
File metadata and controls
110 lines (98 loc) · 1.75 KB
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
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include "parser.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
tline *line;
void
xcd(void){
char *home;
int e;
if(line->commands[0].argv[1]==NULL){
home = getenv("HOME");
e=chdir(home);
if (e<0){
fprintf(stderr,"error al cambiar de directorio\n");
}}else{
e=chdir(line->commands[0].argv[1]);
if (e<0){
fprintf(stderr, "error %s\n",line->commands[0].argv[1]);
}
}
}
void
closePipes(int **p){
int i;
for(i=0;i<line->ncommands-1;i++){
close(p[i][0]);
close(p[i][1]);
}
free(p);
}
void
x(void){
int i;
pid_t pid;
int **p;
if (line->ncommands>1){
p=malloc(sizeof(int*)*line->ncommands-1);
for(i=0;i<line->ncommands-1;i++){
p[i]=malloc(sizeof(int)*2);
pipe(p[i]);
}
}
for(i=0;i<line->ncommands;i++){
pid=fork();
if (pid<0){
fprintf(stderr, "error al crear el hijo\n");
exit(1);
}
if (pid==0){
if (line->commands[i].filename==NULL){
fprintf(stderr,"%s:No se encuentra el mandato\n", line->commands[i].argv[0]);
exit(1);
}
if (line->ncommands>1){
if(i==0){
dup2(p[0][1],1);
}else if(i==(line->ncommands-1)){
dup2(p[i-1][0],0);
}else{
dup2(p[i][1],1);
dup2(p[i-1][0],0);
}
closePipes(p);
}
execvp(line->commands[i].filename,line->commands[i].argv);
exit(1);
}
}
if(line->ncommands>1){
closePipes(p);
}
for(i=0;i<line->ncommands;i++){
wait(NULL);
}
}
int
main(void){
char buf[1024];
printf("msh> ");
while (fgets(buf, 1024, stdin)) {
line = tokenize(buf);
if (line==NULL) {
continue;
}
if(strcmp(line->commands[0].argv[0],"cd")==0){
xcd();
}else{
x();
}
printf("==> ");
}
return 0;
}