Implement << redirection in C

1k views Asked by At

I'm trying to implement << redirection in C, I'm having issues with the code below. I can implement the other three redirection <, >, and >>. I think I need a loop to handle/check the delimiter of <<, How can I handle this problem? When I run the program I get

 /usr/bin/cat: '<<': No such file or directory
 /usr/bin/cat: EOF: No such file or directory

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(void)
{
    char *argv[] = { "/usr/bin/cat", "<<", "EOF", 0 };
    char *envp[] =
    {
        "HOME=/",
        "PATH=/bin:/usr/bin",
        "USER=julekgwa",
        0
    };
    int fd = open(0, O_RDONLY);
    dup2(fd, 0);
    close(fd);
    execve(argv[0], &argv[0], envp);
    fprintf(stderr, "Oops!\n");
    return -1;
}
1

There are 1 answers

1
aragaer On BEST ANSWER

Any kind of redirection is a shell feature. You are using execve which is executing cat directly, not giving shell a chance to do anything.

The following might work:

char *argv[] = { "/bin/bash", "-c", "/usr/bin/cat <<EOF\ntest\nEOF", 0};

But it's unlikely you really want to do that.