Continuously write to a subprocess using popen in C ++

I need to open a subprocess using popen, the process will constantly ask for user input ... The main process should send this data through the channel.

This is my first attempt:

FILE *in; char buff[1024]; if(!(in = popen("cd FIX/fix2/src; java -cp .:./* com.fix.bot", "w"))){ return 1; } while(1){ char buffer[] = { 'x' }; fwrite(buffer, sizeof(char), sizeof(buffer), in); cout << "Wrote!" << endl; usleep(1000000); } 

However, the data is not sent! I need to close the pipe using pclose () so that data is written to the process. How can I ensure that data is recorded without having to close the pipe every time?

+6
source share
2 answers

You want to call fflush(in) to make sure that the buffered data is actually written to the stream.

Also check that java -cp .:./* in the command does not apply to an invalid class path. I think that eventually this will expand to a few arguments if there are more than one file in the current directory and not the actual entries in the classpath.

+1
source

This works for me:

 #include <stdio.h> #include <unistd.h> #include <iostream> int main(int argc, char ** argv) { FILE *in; char buff[1024]; if(!(in = popen("./2.sh", "w"))){ return 1; } while(1) { char buffer[] = "xx\n"; fwrite(buffer, sizeof(char), sizeof(buffer), in); fflush(in); std::cout << "Wrote!" << std::endl; usleep(1000000); } } 

where 2.sh:

 #!/bin/sh read INP echo 'read: ' $INP 

Therefore, I really suspect that the problem is missing \ n.

0
source

Source: https://habr.com/ru/post/987839/


All Articles