views:

63

answers:

4

I'm using popen to open a write pipe and send commands to an application. The problem is that the commands are only sent to the application when I close the pipe.

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 possible wrong?

+2  A: 

fflush(3)

Nikolai N Fetissov
+1  A: 

I just figure it out that I have to flush the pipe to send commands without the need to close it. My fix was:

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
carlfilips
A: 

pipe won't send the data until the end of it is reached. You've gotta tell that this is the end otherwise it will continue to wait for something.

One way of doing that is to do as you do : closing the pipe. Another one is to use fflush (the best in my opinion). You can write a \n too I guess, I haven't wrote C++ for a long time now.

Shahor
I have tried \n, but it won't work. The only way I could make it works is by using fflush.
carlfilips
Yep, because it is the good way to do it :)
Shahor
A: 

From the manpage:

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

This means for a standard implementation, between 512 and 8192 bytes will have to be written before data is flushed automatically to the underlying file descriptor.

Either call fflush(), or better yet, call setvbuf(fp, nullptr, _IONBF, 0);

Matt Joiner