Sunday 29 April 2012

Write your own shell in c

The main shell program which uses fork and exec to fork a process when the user provides a command :download
The shell itself can be forked ,thus multiple terminal can be created and program runs in each of the terminal :


#include<stdio.h>
int main()
{char c;
while(1)
{printf("want to login ? press enter\n");
scanf("%c",&c);
if(fork()==0)
{
system("xterm -e 'path-to-the-executable file of shell program' ");

}
}
}

save it as say main.c


Here create the executable for the shell program after downloading
> gcc filename -o executablename

then put the path to the executable in the above script then run it as

>gcc main.c -o main
>./main

The shell program involves the use of pushd,popd and dirs command which are used to change the directory "pushd directory-path " will take you to that directory and "popd " takes you back to the previous directory
dirs provides the list of directory which is in the stack ,which you have pushed

Also there exist option of altering the path variable wherin "path + path-name" will add the path to the shell and "path - path-name" will remove it from shell
and "path" gives the list of path.The provision of path allows the shell to search for executables at that path.Thus when the user provides a command at the terminal it exhaustively searches for any executable file at all the path list specified corresponding to the user terminal command.




Executing the shell: password and user name is stored in a file named passwords.txt ,note the usage of path and pushd popd options .
pushd , popd allows you to change the directory and go back to the older one similar to the implementation of a stack
The path allows you to specify the location of executable,note i have specified path as /bin which contain all the executables thus allowing ls command to work.
Also in the current directory i have stored my own c file generated executables such as ls1 which does the ls operation.

 Thus you can create your own c files and save the executables in the current or path specified directory and use the same in your shell program.

Happy shelling !!

<A tutorial on shell will be provided shortly>