Consider that we decided to adopt the conventional method for implementing the cd command,i.e we will spawn a new process whenever the cd command is encountered. If you where to explore Linux System Call API, you will find that the only sys call available for changing the directory is the chdir(). The problem with the chdir() is that it can only change the current working directory of the current process. Thus if we are implementing cd as a separate process, it will have no effect on our main process-shell.That's the stage at which the shell built ins kicks in. Built ins are nothing but commands whose implementation is the task of the shell itself. So whenever a built in command is encountered , it is implemented by the bash itself rather than as a separate process.
The below program is the source code for a minimal shell that implements cd as a built in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<unistd.h> | |
#include<string.h> | |
#include<stdio.h> | |
#include<stdlib.h> | |
void main() | |
{ | |
char path[]="/bin/%s",*arg=(char *)malloc(15*sizeof(char)),*cmd=(char *)malloc(15*sizeof(char)),*cmdarg=(char *)malloc(15*sizeof(char)),*cwd=(char *)malloc(70*sizeof(char)); | |
while(1){ | |
printf("paul@linux:~%s$ ",getcwd(cwd,70)); | |
cmdarg=gets(cmdarg); | |
cmd=(char *)strtok(cmdarg," "); | |
arg=(char *)strtok(NULL," "); | |
if(strcmp("cd",cmd)==0){ | |
if(chdir(arg)==-1) | |
perror("Error"); | |
} | |
else if(strcmp("exit",cmdarg)==0) //Type exit to Exit ;) | |
kill(getpid(),9); | |
else{ | |
if(fork()==0){ | |
sprintf(path,"/bin/%s",cmd); | |
if(execl(path,cmd,arg,(char *)NULL)==-1) | |
perror("No such command in /bin"); | |
} | |
else | |
wait(); | |
} | |
} | |
} |
No comments:
Post a Comment