Repository navigation
Expand file tree
/
Copy pathmysh.c
More file actions
93 lines (80 loc) · 1.55 KB
/
Copy pathmysh.c
File metadata and controls
93 lines (80 loc) · 1.55 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//function to get input from user
char* repl_loop()
{
char *line = malloc(1024);
while(1)
{
do
{
printf("adansh> ");
fgets(line,1024,stdin);
if(line == NULL)
{
perror("Memory allocation failed\n");
exit(0);
}
}while(line == NULL || line[0] == '\n');
printf("You entered: %s", line);
return line;
}
free(line);
}
//function to interprate user input
char* interpret(char* line)
{
char *delim = " \t\r\n\a";
char *token;
token = strtok(line, delim);
while (token != NULL)
{
token = strtok(NULL, delim);
}
return token;
}
//function to execute commands
void execute(char **args)
{
if (args == NULL)
{
perror("No command entered\n");
return;
}
//forking a child process
pid_t pid = fork();
if (pid < 0)
{
perror("Fork failed");
return;
}
if (pid == 0 )
{
//child process
if (execvp(args[0], args) == -1)
{
perror("Execution failed");
}
exit(EXIT_FAILURE);
}
else
{
//This is the parent process - wait for the child to complete
int status;
do
{
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
}
//main function
int main()
{
char *input = repl_loop();
char *output =interpret(input);
execute(output)
free(input);
return 0;
}