Pipe question
John Pew
pew at grieg.Eng.Sun.COM
Wed Mar 13 06:33:28 AEST 1991
I'm writing a program which needs to have some data run through
a filter. I do not have the source to the filter I want to call. I
only have the executable. Within my program I need to write to the
filter and then read from the filter. I know how to do one or the other
using either popen() or pipe() but don't know how to do both. I can't
really use popen() since it only supports reading or writing to the
exec'd program. I've included the program I wrote which does not work.
I set up two pipes: one for writing to the filter (I used "tr" to test with)
and one from reading from the filter. When the parent tries to read
from the filter it never returns from the read. Any suggestions would
be appreciated.
John Pew
pew at sun.com
Here's the program:
#include <stdio.h>
char buf[] = "hello there";
char newbuf[64];
main()
{
int pipe1[2], pipe2[2], child;
int fd1, fd2;
int rret;
if(pipe(pipe1)) {
perror("pipe1");
exit(1);
}
if(pipe(pipe2)) {
perror("pipe2");
exit(1);
}
if((child = fork()) == -1)
perror("fork");
else if (child) { /* This is the parent */
close(pipe1[0]);
close(1);
fd1 = dup(pipe1[1]);
close(pipe1[1]);
close(pipe2[1]);
close(0);
fd2 = dup(pipe2[0]);
close(pipe2[0]);
fprintf(stderr,"parent: fd1 %d, fd2 %d\n",fd1,fd2);
if(write(fd1, buf, strlen(buf)) < 0)
perror("writing stream message");
sleep(1);
rret = read(fd2, newbuf, 16);
if(rret < 0) {
perror("read");
exit(1);
}
fprintf(stderr,"parent: rret = %d\n",rret);
} else { /* This is the child */
close(pipe1[1]);
close(0);
fd1 = dup(pipe1[0]);
close(pipe1[0]);
close(pipe2[0]);
close(1);
fd2 = dup(pipe2[1]);
close(pipe2[1]);
execlp("tr", "tr", "a-z", "A-Z", (char *)0);
fprintf(stderr,"unable to execvp tr\n");
}
}
More information about the Comp.unix.questions
mailing list