Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ write data on stdin and get output from stdout

I have one program that calls one tar.. something like popen("tar -zcvf")

I want to write on the stdin... and get the output.. something like tar -zcvf - /path| tar - zxvf -

so.. on one side i'll encapsulate the files from the directory and them send trough the stdout and write on the inverse process.. and send to the stdout of the bash.

I want to do this pipe process..

Read one folder/file and send trought the stdin to the "extract" the content and read the binary output.

I want this, because i can send trought socket data and extract on the other side without the need of disk, i compress and decompress on realtime..

Someone can help me?

I saw i need to do a execl... but all the examples i found was to redirect the stdout of the child to mine.

I will do something like that:

LOOP.
1 Get block of data from stdin
2 Send to child program
3 get the output
4 Do something with the data (send back trough socket)
END_LOOP

OR
LOOP
1 Get block of data from stdin.
2 Send to child program.
END_LOOP
LOOP
1 Get block of data from child program
2 Do something with the data (send back trough socket)
END_LOOP
like image 339
Lefsler Avatar asked Jan 22 '26 01:01

Lefsler


1 Answers

You can't use popen for this; popen is always unidirectional. You can set up something along these lines using pipe and fork directly (but it's a lot more work than popen). If you do, however, you have to be very, very careful. A pipe can only hold a finite amount of data. Try to write more, and the write waits until the space is available. So you can easily end up in a situation where the child process is waiting for you to read something on its output pipe, in order to create more space in the pipe, and your process is waiting for the child to read something so that there will be more room in hhe pope. I've done this once in the past, but sort was one of the programs in the loop—and you're guaranteed that sort won't try to write anything until it has seen end of file on its input.

like image 78
James Kanze Avatar answered Jan 24 '26 19:01

James Kanze