cexecvp

Will EXECVP system call supports IO redirections


Will EXECVP system call supports IO redirections

That means is this give desired output

char *args[]={"cat","A.txt","B.txt",">","C.txt",NULL};
execvp(args[0],args);

I mean will the data in A.txt and B.txt goes to C.txt

If no why ?

UPD : I have asked two doubts in comment please clarify it


Solution

  • This is technically not an answer to your question, that has been answered in the comments. But an explanation to how you can do redirection with execvp

    When starting a new program with execvp, it will inherit the current file descriptor. So if you setup file descriptor 1 (which is used for stdout) to be redirected to "C.txt" before calling execvp, the new program will write to "C.txt":

    // Open "C.txt" for writing, creating it if it doesn't exist, or
    // clearing its content if it does exist.
    // `mode` should be set as appropriate 
    //
    int fd = creat("C.txt", mode);
    if (fd == -1)
    {
       // Swap out error handling to suit your needs
       perror("open failed");
       exit(EXIT_FAILURE);
    }
    
    // We want new process to have "C.txt" on file descriptor 1
    if (dup2(fd, 1) == -1)
    {
       perror("dup failed");
       exit(EXIT_FAILURE);
    }
    
    
    // "C.txt" is now writable on file descriptor 1, so we don't need the
    // old one. Actually, the old one could confuse the new executable.
    close(fd);
    
    
    // We can now execute new program. It will inherit current open 
    // file descriptors and it will see "C.txt" on file descriptor 1
    char *args[]={"cat","A.txt","B.txt",NULL};
    execvp(args[0],args);
    
    // If we reach this point, `execvp` failed.
    perror("execvp failed");
    exit(EXIT_FAILURE);