0

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).

ffledgling
  • 11,502
  • 8
  • 47
  • 69
  • `execl` is a variadic function, so no checking is done on the arguments -- you can pass pretty much anything without it giving an error or warning. – Jerry Coffin Aug 22 '12 at 20:32

1 Answers1

5

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    I don't get the "You're seducing execl into using a small integer as a pointer" Part. And yes I was wondering if grep would understand file descriptors. – ffledgling Aug 22 '12 at 20:35
  • Well, you said it yourself. *I know that execl takes only const char arg**. So it has no choice than to think the 4 or 5 you're passing is a valid pointer. Which it's not. – cnicutar Aug 22 '12 at 20:36
  • 1
    `execl` takes `char *`s, not `int`s. So he's saying you're passing an `int` where a `char *` is expected (by passing `fd` as the third argument to `execl`. – Sean Bright Aug 22 '12 at 20:37
  • Also grep only seems to read only from a file according to the man page. (A quick test `grep pattern < "This is pattern"` also seems to support this) So how will re-directing the the required text to the stdin help grep read it? (I apologize in advance for any technical errors I might have made here, I'm still learning) – ffledgling Aug 22 '12 at 20:41
  • My bad again. It *does* work on stdin. Sorry and Thanks for the help! – ffledgling Aug 22 '12 at 20:44