Using popen to write to the pipe only sends data when the pipe is closed

I use popen to open a recording channel and send commands to the application. The problem is that commands are only sent to the application when I close the channel.

FILE * fp = open(target_app, "w");
fwrite(command, 1, command.size(), fp);
getchar(); //wait for a key, because I don't want to terminate the application
pclose(fp); // at this point, the command is sent

What could be wrong?

+3
source share
4 answers

I just understand that I need to clean the pipe to send commands without having to close it. My fix:

FILE * fp = open(target_app, "w");
fwrite(command, 1, command.size(), fp);
fflush(fp);
getchar(); //wait for a key, because I don't want to terminate the application
pclose(fp); // at this point, the command is sent
+2
source

, . , , -.

- , : . - fflush (, ). \n, , ++ .

0
source

From the man page:

Note that output popen() streams are fully buffered by default.

This means that for a standard implementation, between 512 and 8192 bytes must be written before the data is automatically cleared to the base file descriptor.

Call fflush()or, better yet, callsetvbuf(fp, nullptr, _IONBF, 0);

0
source

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


All Articles