c - Receiving error code during output redirection using execvp -


i trying redirect output ls file, in shell created in c. type in:

ls > junk  

and out is:

ls: cannot access >: no such file or directory 

then if use ctrl-d exit shell prints results of ls command screen before exiting. tried use print statements figure out happening , no print statements printed after:

dup2(f, stdout_fileno); tried  dup2(f, 1); 

code:

            pid = fork();              if(pid == 0)             {               // arguments execvp null terminated array                       for(i = 0; <= count; i++)                     {   if(i == count)                         {                             args[i] = (char *)malloc(2 * sizeof(char));                             args[i] = '\0';                         }                         else                         {                             str = strlen(string[i]);                             args[i] = malloc(str);                             strcpy(args[i], string[i]);                                              }                     }                                         if(count == 1)                 {                  }                 else if(strcmp(string[(numargs + 1)], ">") == 0) //numargs number of arguments typed in user                 { // printed out string[numargs+2] previously, , says junk                     int f = open(string[(numargs + 2)], o_wronly | o_creat | o_trunc, s_irusr | s_iwusr | s_irgrp | s_iroth);                      if(f < 0)                     {                         printf("unable open output file\n");                         status = 1;                     }                     else                     {                         fflush(stdout);                         dup2(f, stdout_fileno);                          close(f);                      }                 }                    j = execvp(string[0], args); // first element of string array first thing user enters command ls in case 

the file called junk gets created, gets placed in junk. have been struggling while figuring out why redirection won't work appreciated. thanks.

you cannot use execvp parse shell commands.

the redirection (>) character understood shell (e.g., bash, sh, ksh) , execvp executes command pass directly. not try , interpret arguments , create file redirections, etc.

if want need use system call. see system(3)

similarly, other special shell characters (pipe, *, ?, &, etc) won't work.


Comments