Using grep in execl with file descriptor
-
27-06-2021 - |
Question
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow