-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
82 lines (64 loc) · 1.07 KB
/
shell.c
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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
char *getstr(char *string, int n, FILE *file)
{
char *result;
result = fgets(string, n, file);
if(!result)
return result;
if(string[strlen(string) -1] == '\n')
string[strlen(string) - 1] = 0;
return(string);
}
int main()
{
char line[1000];
char *token;
char *args[10];
while(1)
{
printf("\n$ ");
getstr(line, 1000, stdin);
char *s = "&";
int bg = 0;
args[0] = strtok(line, " ");
int i = 1;
do
{
token = strtok(NULL, " ");
args[i] = token;
i++;
} while(token !=NULL);
if(!strcmp(args[i-2], s))
{
args[i-2] = NULL;
bg = 1;
}
fflush(NULL);
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("failed to process Forking\n");
}
if(pid != 0)
{
printf(" parent process with id: %d\n", (int)getpid());
if(bg)
{
printf("Waiting");
wait(NULL);
}
}
else
{
printf(" child process with id: %d\n", (int)getpid());
if(execvp(args[0], args) == -1)
printf("FAILED");
execvp(args[0], args);
}
}
return 0;
}