/
myshell1.c
109 lines (92 loc) · 2.08 KB
/
myshell1.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
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
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
#include<assert.h>
#define MAXLINE 4096
void show(){
char *pwd, *shortpwd;
char *saveptr, *tmp;
pwd = get_current_dir_name();
tmp = pwd;
//printf("%s\n", pwd);
tmp = strtok(pwd, "/");
// printf("pwd: %s\n", pwd);
//printf("tmp: %s\n", tmp);
while(tmp = strtok(NULL, "/"))
{
printf("tmp: %s\n", tmp);
shortpwd = tmp;
}
// printf("shortpwd: %s\n", shortpwd);
printf("[%s]", shortpwd);
free(pwd);
}
void setup(){
signal(SIGINT,SIG_IGN); //ignore ctrl+c
signal(SIGQUIT,SIG_IGN); //ignore \+ctrl
}
void getcmd (char *buf ,char **args){
while(*buf !='\0')
{
while((* buf==' ')||(* buf== '\t')||(* buf == '\n'))
*buf++ = '\0';
*args++ = buf;
while((* buf!='\0')&&(* buf!=' ')&&(* buf!='\t')&&(*buf!='\n'))
buf++;
}
*args = '\0';
}
void do_cd(char *argv){
assert(argv);
char *dirtmp;
if(argv == NULL || strcmp(argv, "~") == 0){
dirtmp = getenv("HOME");
if(!dirtmp){
perror("HOME not set");
exit(1);
}
chdir(dirtmp);
}else{
dirtmp = argv;
if(chdir(dirtmp) != 0){
perror("wrong file or dir");
exit(1);
}
}
}
int main(int argc, char * argv[]){
char buf[MAXLINE];
pid_t pid;
int status;
char * args[64];
show();
setup();
while(fgets(buf,MAXLINE,stdin) != NULL) {
if(buf[strlen(buf) - 1]='\n'){
buf[strlen(buf) - 1]=0;
}
getcmd(buf, args);
// printf("%s\n", *args);
// printf("%s\n", *(args+1)); // need to: ls -al, then can ture!
// printf("%x\n", args);
if(!strcmp(*args, "exit")){
exit(EXIT_SUCCESS);
}else if(!strcmp(*args, "cd")){
do_cd(*(args+1));
show();
continue;
}
if((pid = fork())<0){
printf("fork error");
}else if(pid == 0){
execvp(*args,args);
printf("couldn't execute: %s\n",buf);
show();
}
if(pid = waitpid(pid, &status, 0))
show();
}
exit(0);
}