Advertisement

popen and fork goodness

Started by July 26, 2004 05:56 PM
3 comments, last by NicoDeLuciferi 20 years, 1 month ago
Ok here's the situation. I'm writing a C application on a POSIX platform and I want to spawn grep to match some text for me. I want to be able to redirect the child processes input and output so I can write the text I want to find the match in, and then read from it's stdout to get the match. I've seen popen, and doesn't seem to be working for me. It seems as if I can only setup either a read stream, or a write stream, but not both. I also looked into using pipe/fork/exec, but I have no clue how to remap stdin/stdout to an open file descriptor in the child process. Any help would be much appriciated :) - Kevin
Kevin.
Quote: Original post by Krumble
I've seen popen, and doesn't seem to be working for me. It seems as if I can only setup either a read stream, or a write stream, but not both.
My solution was to just open two pipes, one for reading and one for writing. Not very elegant, but it works.

Quote:
I also looked into using pipe/fork/exec, but I have no clue how to remap stdin/stdout to an open file descriptor in the child process.
I think dup2() is what you want, but I've never gotten this method to work either.
Advertisement
works like this...

fork()
; pipe(filedes);
; dup2(filedes[0],0);
; dup2(filedes[1],1);
; fork()
; ; exec(...);
; R/W into fd's.

(using ; for whitespace cux i'm too lazy to put tags in there)

that's a rough sketch. you shoudl get the jist of it from that.
Given that you're going to be giving grep input from your app anyway, I would've thought it'd be easier to match in your own code rather than having to pipe to grep to match for you. If it's regex that you need, there are plenty of open source regex libraries available, or if you need plain text searching, I'm sure there are libraries for that too.

Unless there's some other weird reason you need to use grep, of course...

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
int fds[2];pipe(fds); // creates the pipeif (fork() == 0) {  close(1); // closes STDOUT  dup(fds[1]); // sets the pipe-write-end to STDOUTs fileno  close(fds[0]); // closes the unused pipe-end  execl(..)	}close(0); // closes STDINdup(fds[0]); // sets the pipe-read-end to STDINs filenoclose(fds[1]); // closes the unused pipe-end char str[MAX_RET_VAL];int res;// read the output from the exec:d program through the pipewhile ((res=read(fds[0],str,MAX_RET_VAL)) != 0) { ;}


Or something like that..

This topic is closed to new replies.

Advertisement