-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
75 lines (58 loc) · 1.68 KB
/
shell.c
File metadata and controls
75 lines (58 loc) · 1.68 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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pwd.h>
#define ARGVMAX 100
#define LINESIZE 1024
#define STRINGSIZE 500
int makeargv(char *s, char* argv[ARGVMAX]) {
// pre: argv is
// out: argv[] points to all words in the string s (*s is modified!)
// return: number of words pointed to by the elements in argv (or -1 in case of error)
int ntokens;
if ( s==NULL || argv==NULL || ARGVMAX==0)
return -1;
ntokens = 0;
argv[ntokens]=strtok(s, " \t\n");
while ( (argv[ntokens]!= NULL) && (ntokens<ARGVMAX) ) {
ntokens++;
argv[ntokens]=strtok(NULL, " \t\n");
}
argv[ntokens] = NULL; // it must terminate with NULL
return ntokens;
}
void runcommand(char* argv[]) {
pid_t rc = getpid();
pid_t pid = fork();
if(pid == 0){
char const* f = argv[0];
execvp(f, argv);
}
else{
waitpid(pid, NULL, 0);
}
return;
}
void init(char* currentDir, int maxCurrentDir, char* currentUser, int maxCurrentUser, char* host, int maxHost){
getcwd(currentDir, maxCurrentDir);
getlogin_r(currentUser,maxCurrentUser);
gethostname(host, maxHost);
}
int main() {
char line[LINESIZE];
char* av[ARGVMAX];
char cwd[STRINGSIZE];
char cu[STRINGSIZE];
char host[STRINGSIZE];
init(cwd, STRINGSIZE, cu, STRINGSIZE, host, STRINGSIZE);
system("clear");
printf("[%s@%s]-%s:", cu, host, cwd); fflush(stdout); //writes the prompt on the standard output while ( fgets( line, LINESIZE, stdin ) != NULL ) {
while ( fgets( line, LINESIZE, stdin ) != NULL ) {
if ( makeargv( line, av) > 0 )
runcommand( av );
printf("\n[%s@%s]-%s:", cu, host, cwd); fflush(stdout);
}
return 0;
}