Search code examples
cgrepexecfile-descriptorunistd.h

Using grep in execl with file descriptor


I'm trying to do the following:

 execl("/bin/grep","grep","print",fd,NULL);

where fd is a file descriptor. So basically this should grep for "print" in the file pointed to by fd. It doesn't seem to work although I get no compile errors/warnings. It works when I give a filename such as "Something.txt" instead of the fd

Can someone tell me why this isn't working? (I know that execl takes only const char arg* but as I said no compile errors/warnings).


Solution

  • There are 2 issues:

    • You're seducing execl into using a small integer as a pointer
    • You're expecting grep to understand file descriptors

    If I understand your question correctly, right before you exec, you should redirect the descriptor into STDIN_FILENO. Something like:

    dup2(fd, STDIN_FILENO);
    execl("/bin/grep", "grep", "print", NULL);
    

    This should work because grep analyzes its stdin when no input files are provided.