15 April 2013

CREATE YOUR OWN LINUX SHELL


First to create linux shell ,you have to understand how shell actually works...
The parent process is the shell itself..
Each time when we type in some command with its arguments as a string of characters and hit enter ,the parent process creates a new child process to handle it.
The parent process parses the whole string ,separate command and its arguments ,build a array of strings with this command and arguments ,pass this array to the function that can be executed only by child process.Inside this function execvp is used which does the actual task of executing
since exec family of functions replaces the original process (in our case child process) and do not return on successful completion,the child process disappears at last.
In the mean time parent process (shell ) wait for child process to complete or disappear ,so that it can accept next command.
and again the whole process repeats itself and so on...
Lets do some code
[cpp]
void childprocess(char *arg[]){
execvp(arg[0],arg);
printf("nERROR:file or directory does not existn");
}
int main(){
char command[100],*argv[20];
int t=0;
pid_t pid;
int status;
printf("nWELCOME TO QUICK SHELL VERSION 3.33 n");
while(1){
printf("programmer@work>");
gets(command);
argv[t]=strtok(command," ");
while((argv[++t]=strtok(NULL," "))){
}
if((pid=fork())==0)
{
childprocess(argv);
}
if(pid){
wait(&status);
}
t=0;
}
}
[/cpp]
You are not going to get better then this in such few lines of code..
ok may be some of you can make better then this .who knows..?
you can always find one genius
some more thing i want to talk about
have you heard about system call
[cpp]
int main(){
system("ls -l");
}
[/cpp]
This function is executed with the help of fork() ,waitpid() and exec function family
SOME NOTE ON vfork():
necessity drives invention.
In computer world this statement is 100 % valid.
why vfork() was created at all? consider this program...
[cpp]
int main(){
char buf1[10000],buf2[10000],buf3[10000];
pid_t pid;
if((pid=fork())==0){
execl("/bin/ls","ls","-l",NULL);
_exit(EXIT_FAILURE);
}e
}
[/cpp]
surely there is something wrong here.what? where is it?
in memory my dear in ancient times of computers ,the memory was sold at the price of gold.
since the fork will create child process exactly the same as parent,in programs similar to above why give him so much amount of memory if finally child has to execute (using exec*) some external program and disappear himself.The called program will be allotted its own memory space and the memory allotted to child (copied from parent) is just a waste.
To handle this situation vfork() was created.It uses copy on right technique in which initially both child and parent are alloted same memory space and

SHARE THIS

Author:

0 comments: