This is an old post, but I also had a need several years ago to use a popen() like call in a Windows environment. As several of the comments in the answer here have noted, using the Windows API to implement anything close to the classic POSIX popen()
is interesting.
I created an implementation which I submitted to Code Review . This implementation uses pipes
to stdin
and from stdout
, as well as Windows methods for CreateProcess(...)
.
The linked code is designed to be built into a dll with a very small API.
int __declspec(dllexport) cmd_rsp(const char *command, char **chunk, unsigned int size);
Simple example of usage:
#include "cmd_rsp.h"
int main(void)
{
char *buf = {0};
buf = calloc(100, 1);
if(!buf)return 0;
cmd_rsp("dir /s", &buf, 100);
printf("%s", buf);
free(buf);
//or a custom exe
char *buf2 = {0};
buf2 = calloc(100, 1);
cmd_rsp("some_custom_program.exe arg_1 arg_2 arg_n", &buf2, 100);
printf("%s", buf2);
free(buf2);
return 0;
}
It takes any command that can be for example issued from stdin
, creates a separate process to execute the command, then returns all response content (If there is any) to a buffer, and does this without displaying the CMD window popup. The buffer grows as needed to accommodate size of response.