I am trying to build a shell in C language for OS project. The problem is coming when I am doing redirection part. ls
is working fine, but when I do ls > somefile
. It gives me an error " ls: cannot access >: No such file or directory ". Here is that part of my code
while(in){
argv[c]=strdup(in); \\in is output of strtok applied on input string
in=strtok(NULL,"\n , ");
c++;
}
argv[c]=NULL;
int rc=fork();
if(rc==0){
int flag = 0;
int index = 0;
int i;
for(i= 0; i <c;i++)
{
if(strcmp(argv[i],">") == 0)
{
flag = 1;
index = i+1;
}
if(flag == 1)
{
fclose(stdout);
fopen(argv[index],"w+");
}
execvp(argv[0],argv);
}
else if(rc>0){
(void) wait(NULL);}
}
return 0;
That error from ls
is telling you that you passed >
to ls
as an argument.
So let us look at your execvp
call:
execvp(argv[0],argv);
So you are using the entirety of argv
as the arguments to the spawned ls
.
Where, in the processing above that call, are you removing the redirection arguments that you've already handled from argv
so that ls
doesn't see them?
Side note: Are you assuming that that fopen
will assign your newly opened file the fd previously used by stdout
? That seems like an unwise assumption to me (even if it normally works).
Oh, and your indentation could use some work.