Dec 26, 2011 at 5:22pm UTC
I'm trying to use pipes to write some data on a program stdin and get the stdout.
I found this one on the internet and changed it, (the original didn't seems to work to):
#define WRITE 1
#define READ 0
using namespace std;
int fd_in, fd_out,
if(fork() == 0)
close(fd_out[READ]); dup2(fd_out[WRITE], WRITE);
dup2(fd_out[WRITE], WRITE); //stdout -> pipe's write (everything what would go to stdout will go to the pipe's write...
execlp("sort", "sort", NULL);
write(fd_out, "c\n", 2);
write(fd_out, "a\n", 2);
write(fd_out, "b\n", 2);
while((c = read(fd_in, buf, 5)) > 0)
write(1, buf, c);
I need to write some data on the sort's stdin and get the stdout, someone can help me?
Dec 26, 2011 at 6:20pm UTC
Sorry, it was my seccond post, so i didn't noticed the code tag.
I'm calling like
echo "text" | myprogram...
and myprogram calls another one and send my stdin as stdin to the program and get the stdout...
If i want to do something like
cat file.txt | ./myprogram > tarfile.zip i should be able to do that, because my program needs to redirect the call to the output.
In this example i'll get the cat as input and send to the "zip" process, get the output of the zip process and send his output to my output.
Dec 26, 2011 at 6:57pm UTC
Must you use a pipe to get the stdin input?
Because if not you could use for the input.
fread(a, b, c, stdin);
Then you use two pipes and dup2(), like you tried.
And finally .
fwrite(a, b, c, stdout);
If you need to use write() and read() just remember that 0 = stdin and 1 = stdout.
Dec 26, 2011 at 10:08pm UTC
Just taking a quick glance at your code, you're doing dup2 on the child's stdout twice, I don't know what the effect of this is, but I don't think it's right. Also, you haven't closed either end of either pipe in the parent.
Dec 27, 2011 at 11:09am UTC
I tried to write on the stdout and read on my stdin.. but i need to get the stdout of the execl program
Dec 27, 2011 at 11:10am UTC
fixed the duplicated dup2.. but still the same thing
Dec 27, 2011 at 12:10pm UTC
How can i do that... the close before the dup dont work like that?
Dec 27, 2011 at 12:19pm UTC
The close before the dup are in the child, not the parent. I suggest you go and read the book I provided a link to and learn how fork and pipe work.
Dec 27, 2011 at 12:50pm UTC
I just found how to exec more than one process.
I need to start one process, send data to it e receive the returned data from it.