Redirection inside call to execvp() not working

后端 未结 3 704
既然无缘
既然无缘 2020-12-09 23:55

I\'ve been implementing a small program that executes a given command using execvp(). It works fine when not using redirection, but when I run a command such as:

<         


        
相关标签:
3条回答
  • 2020-12-10 00:38

    It seems like the easiest thing to do is:

    execlp( "/bin/sh", "/bin/sh", "-c", "cat file1.txt > redirected.txt", (char *)NULL );
    

    You can do the same with execvp.

    0 讨论(0)
  • 2020-12-10 00:43

    You can use system() if you really want to use that sort of syntax. As you noted, redirection and wildcard expansion and a whole bunch of other things are handled by the shell on Unix-like systems.

    The way to do it with fork looks something like this:

    int kidpid;
    int fd = open("redirected.txt", O_WRONLY|O_TRUNC|O_CREAT, 0644);
    if (fd < 0) { perror("open"); abort(); }
    switch (kidpid = fork()) {
      case -1: perror("fork"); abort();
      case 0:
        if (dup2(fd, 1) < 0) { perror("dup2"); abort(); }
        close(fd);
        execvp(cmd, args); perror("execvp"); abort();
      default:
        close(fd);
        /* do whatever the parent wants to do. */
    }
    
    0 讨论(0)
  • 2020-12-10 00:44

    Your "small program that executes a given command" is essentially a shell. Since you are writing a shell, it is your job to implement redirections with whatever syntax you desire. The > redirection operator is not a feature of the kernel, it is a shell feature.

    To implement sh-style redirection, you must parse the command, locate the redirection operators, open the files and assign them to input/output descriptors. This must be done before calling execvp. Look up the dup2 system call.

    0 讨论(0)
提交回复
热议问题