i am working a project about Shell in unix.
i want to exe commands like ls, ls < out.txt , sort < in.txt > out.txt
i got a input from the terminal and my program ends while i send EOF.
my ls command doesnt run but the command: ls > out.txt is doing fine. when i am trying to execute ls after this it doesnt work i need to write ls >
i am taking some segmetion faults though
here is some code any help would be appreciated
Code:
#include "2_shell.h"#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc,char** argv)
{
char str[512];
int status;
int i;
pid_t pid, waitPid;
char* hey;
int flag_in=-1,flag_out=-1;
int out;
char * target_output=">";
char * output;
printf("\n--Welcome to auebshell1--\n");
printf(">");
while(fgets(str,512,stdin)){
hey =makeString(str);
char ** tokens=tokenizer(hey,&i);
flag_out=findSympol(tokens,target_output,i);
printf(" output %d ",flag_out);
if(flag_in<0){
if(flag_out>0){
output=tokens[flag_out+1];
out = open(output,O_WRONLY|O_CREAT,0700);
dup2(out,STDOUT_FILENO);
close(out);}
}
pid = fork();
if(pid < 0){
perror("ERROR: Child couldnt be created!\n");
return -1;
}
if(pid == 0){
execlp(tokens[0],tokens[0],NULL);
perror("There is no such instruction!!\n");
return -1;
}
else{
waitPid = wait(&status);
if(waitPid == -1){
perror("Failed to wait for child to be executed! \n");
}
}
printf("\n--Welcome to auebshell1--\n");
printf(">"); }
printf(" auebshell terminated!\n"); return 1;
}
char *makeString(char *input){
int i;
char *returnString;
returnString = (char *)malloc(sizeof(char)*strlen(input)-1);
for(i = 0; i < strlen(input)-1;i++){
returnString[i] = input[i];}
return returnString;
}
char** tokenizer(char* Array,int * a){
int counter=1;
char* *returner=NULL;
char* tokens;
tokens =strtok(Array," ");
while(tokens){
returner=realloc(returner,sizeof(char*)*counter);
if(returner==NULL)
exit(-1);//memory fail//
returner[counter-1]=tokens;
counter++;
tokens=strtok(NULL," "); }
returner=realloc(returner,sizeof(char*)*(counter));
if(returner==NULL)
exit(-1);
returner[counter]=0;
*a=counter;
return returner;}
int findSympol(char ** Tokens,char * target,int size)
{
int i;
int flag;
for(i=0;i<size;i++){
flag=strcmp(target,Tokens[i]);
if (flag==0) {
thesis=i;
return thesis;}
}
return thesis;
}