I want to redirect stdout and stdin in a specific file which would be given in argv array.
For instance when I enter a command like - ./shell ls > test
it should be redirected to the "test" file, now I am bit confuse because without writing any code it automatically redirects to that file, I want to do it manually, secondly, when I enter a command like- ./shell ls < test, the stdin should be redirected. I tried to find a file name and ">" or "<" sign using argv[argc-1] and argv[argc-2], but it seems that when I use ">" and a filename afterwards, the output prints(the arguments before ">" "<" sing) in that file instead of getting that name and a sign.
Basically, I am creating a shell command using execvp() and fork().
Here is my code, I am able to redirect stdout in a static file.
void call_system(char *argv[],int argc)
{
int pid;
int status=0;
signal(SIGCHLD, SIG_IGN);
int background;
/*two process are created*/
pid=fork();
background = 0;
if(pid<0)
{
fprintf(stderr,"unsuccessful fork /n");
exit(EXIT_SUCCESS);
}
else if(pid==0)
{
//system(argv[1]);
/*argument will be executed*/
freopen("CON","w",stdout);
char *bname;
char *path2 = strdup(*argv);
bname = basename(path2);
execvp(bname, argv);
fclose (stdout);
}
else if(pid>0)
{
/*it will wait untill the child process doesn't finish*/
//waitpid(pid,&status,0);
wait(&status);
//int tempid;
//tempid=waitpid(pid,&status,WNOHANG);
//while(tempid!= pid);// no blocking wait
if(!WIFEXITED(status) || WEXITSTATUS(status))
printf("error");
exit(EXIT_SUCCESS);
}
}