Repository navigation
Expand file tree
/
Copy pathproc.c
More file actions
141 lines (118 loc) · 2.96 KB
/
Copy pathproc.c
File metadata and controls
141 lines (118 loc) · 2.96 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
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
141
#include "proc.h"
#include "redir.h"
#include "util.h"
void havechildren(char * strptr, unsigned * stateptr)
{
char tokenptr[MAXLINESIZE];
char * remainder[MAXARGS];
unsigned operation;
int i;
for(i=0;i<MAXARGS;++i)
remainder[i] = (char *) 0x0;
/*** Test for various symbols and set flags ***/
backgroundtest(strptr,stateptr);
operation = operatortest(strptr,stateptr);
/*** Clean up the string a bit ***/
chomp(strptr);
/*** Break the commands into tokens ***/
strncpy(tokenptr,strptr,MAXLINESIZE);
tokenize(tokenptr, remainder);
if (IS_REDIRECT)
{
redirectionfork(tokenptr, remainder, stateptr, operation);
}
else if (IS_PIPED)
{
pipefork(tokenptr, remainder, stateptr);
}
else
{
ordinaryfork(tokenptr, remainder, stateptr);
}
operation = 0x0;
TURN_BACKGROUND_OFF
TURN_REDIRECTION_OFF
TURN_PIPE_OFF
}
void ordinaryfork(char * tokenptr, char ** remainder, unsigned * stateptr)
{
int status = 0;
/*** Create a new child process. ***/
pid_t childpid = fork();
if (childpid == 0)
{
if (execvp(tokenptr, remainder) < 0)
perror("execvp error");
exit(0);
}
else if(childpid == -1)
{
perror("fork error");
}
else
{
/*** Parent does not wait for child. ***/
if (IS_IN_BACKGROUND)
{
waitpid(childpid, &status, WNOHANG);
if(status < 0)
perror("wait error");
}
/*** Parent does wait for child. ***/
else
{
if(wait(0) < 0)
perror("wait error");
}
}
}
void pipefork(char * tokenptr, char ** cmdarray, unsigned * stateptr)
{
int status = 0;
int fd[2];
int readsize = 0;
pid_t firstpid;
pid_t secondpid;
/*** Create a pipe. ***/
if (pipe(fd) < 0)
perror("pipe error");
/*** Create two children. ***/
firstpid = fork();
if (firstpid < 0)
perror("fork error");
else if (firstpid > 0)
{
waitpid(firstpid, &status, WNOHANG); /*** Parent ***/
secondpid = fork();
if (secondpid < 0)
perror("fork error");
else if (secondpid > 0)
{
waitpid(firstpid, &status, WNOHANG); /*** Parent ***/
}
else
{
/*** Second child. ***/
close(fd[1]);
/*** Exec Second Command ***/
if (execvp(cmdarray[1], remainder) < 0)
perror("execvp error");
exit(0);
}
}
else
{
/*** First child... ***/
close(fd[0]);
/*** Exec First Command ***/
if (execvp(cmdarray[0], cmdarray) < 0)
perror("execvp error");
exit(0);
}
}
void redirectionfork(char * tokenptr, char ** remainder, unsigned * stateptr, unsigned operation)
{
/*** Open file handler. ***/
/*** Create a child. ***/
/*** In child, redirect. ***/
}