C C C C C
C C C C C
h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
pid_t my_fork() ;
int process_args(char*, char***) ;
int isPiped(char *);
int execute_piped_command(char *);
/**
This program acts as a shell and executes simple commands.
It relies on the PATH env varibale to search the program.
To exit the program press Ctrl + C
**/
int main(int argc, char *argv[]){
pid_t pid ;
char line[255] ;
piped = isPiped(line);
if(piped==1){
pid = fork();
if(pid==0){
execute_piped_command(line);
}
wait(&status);
}else{
process_args(line,arg_list) ;
k=0;
while(arg_list[k]!=NULL){
j=0;l=0;
bflag=0;
while(arg_list[k][j+1]!=NULL){
++j;
}
if(strcmp(arg_list[k][j],"&")==0){
bflag=1;
arg_list[k][j]=NULL;
}
if(arg_list[k][j]!=NULL){
while(arg_list[k][j][l+1]!='\0'){
++l;
}
if((arg_list[k][j][l]=='&')){
bflag=1;
arg_list[k][j][l]='\0';
}
}
pid = my_fork() ;
if(pid ==-1){
perror("fork failed\n") ;
exit(1) ;
}else if((pid > 0)&&(bflag==0)){
wait(&status) ;
++k;
}else if((pid>0)&&(bflag==1)){
++k;
}else{ // The child Process
if(execvp(arg_list[k][0], arg_list[k])==-1)
{
int i = 0 ;
while(arg_list[k][i] != NULL){
printf("%d:\t%s\n",
i, arg_list[k][i]) ;
++i ;
}
perror("Child process could not
exec\n") ;
exit(22) ;
}
}
}
}
}
int process_args(char *line, char ***args_list){
int i = 0 ;int j=0; char * process_list[256];
char *token ;char *token1;
token = strtok(line, ";");
while(token !=NULL){
process_list[i]=(char*)malloc(255);
strcpy(process_list[i],token);
token=strtok(NULL,";");
++i;
}
process_list[i]=NULL;
i=0;
while(process_list[i]!=NULL){
j=0;
//store the process name in arg_list[i][0] and the arguments
in arg_list[i][1] and the subsequent cells.
while(token1!=NULL){
args_list[i][j]=(char*)malloc(255);
strcpy(args_list[i][j],token1);
token1=strtok(NULL," ");
++j;
}
args_list[i][j]=NULL;
++i ;
}
args_list[i]=NULL;
return 0 ;
}
pid_t my_fork(){
static int count = 0 ;
count++ ;
if(count <= 20){
return(fork()) ;
}else{
return -1 ;
}
}
strcpy(prog2, token) ;
process_args(prog1,arg_list1);
process_args(prog2,arg_list2);
pipe(fd) ;
if(fork() > 0){ // executes prog1
close(fd[0]) ;
dup2(fd[1],1) ;
execvp(arg_list1[0][0], arg_list1[0]) ;
}else{ // executes prog2
close(fd[1]) ;
dup2(fd[0],0) ;
execvp(arg_list2[0][0], arg_list2[0]) ;
}
return -1 ;
}