Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/wait.h>
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <dirent.h>
- int parse(char* st, char** toks)
- {
- char* tok = strtok(st," \t");
- int t = 0;
- while((tok != NULL) && (t < 10))
- {
- toks[t] = tok;
- t++;
- tok = strtok(NULL," \t");
- }
- toks[t] = NULL;
- return t;
- }
- void f_echo(char* st)
- {
- write(1,st,strlen(st));
- //write(1,"\n",1);
- }
- void f_cd(char* st)
- {
- chdir(st);
- }
- void f_pwd()
- {
- char dir[50];
- getcwd(dir, 50);
- write(1,"Current directory")
- write(1,dir,strlen(dir));
- write(1,"\n",1);
- }
- void f_ls(char* st)
- {
- DIR* dir;
- struct dirent* de;
- dir = opendir(st);
- while((de = readdir(dir)) != NULL)
- {
- write(1, de->d_name, strlen(de->d_name));
- write(1,"\n",1);
- }
- close(dir);
- }
- int main()
- {
- char cmd[256];
- char* toks[10];
- int t = 0;
- do{
- write(1,">",1);
- int n = read(0,&cmd,256);
- cmd[n-1] = '\0';
- int tt = parse(cmd, toks);
- if (strcmp(toks[0],"cd") == 0)
- {
- f_cd(toks[1]);
- t=1;
- }
- if (strcmp(toks[0],"echo") == 0)
- {
- int c = 1;
- while (c < tt)
- {
- f_echo(toks[c]);
- write(1," ",1);
- c++;
- }
- write(1,"\n",1);
- t=1;
- }
- if (strcmp(toks[0],"pwd") == 0)
- {
- f_pwd();
- t=1;
- }
- if (strcmp(toks[0],"myls") == 0)
- {
- if (tt==1)
- {
- f_ls("./");
- }
- else
- {
- f_ls(toks[1]);
- t=1;
- }
- }
- if (t == 0)
- {
- int p=fork();
- if (p==0)
- {
- execvp(toks[0],toks);
- perror("Unknown command");
- exit(1);
- }
- else if (p>0)
- {
- wait(&p);
- }
- }
- } while (strcmp(toks[0],"exit") != 0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement