2

我正在尝试做的是创建一个程序,该程序将在运行时以“--exampleparameter --exampleparameter2”作为cli输入打开examplecliprogram.exe,等待examplecliprogram.exe终止,然后获取输出并做一些有用的事情用它。我希望 examplecliprogram.exe 在后台运行(而不是在另一个窗口中打开),而 examplecliprogram.exe 的输出显示在运行开销程序的窗口中。

到目前为止,我已经探索了诸如 popen()、ShellExecute() 和 CreateProcess() 之类的选项,但我似乎无法让它们中的任何一个正常工作。

首先,我希望这个程序能够在 Windows 环境中独立运行,并且与 Linux 的兼容性将是一个额外的好处。

编辑:我通过调用 system("arguments") 找到了一种解决方案。我不知道这是否是一个很好的解决方案,可以很好地转移到 gui,但至少它解决了基本问题。

4

4 回答 4

0

此代码在 Windows 和 Unix 上运行(我在 Visual Studio、Cygwin 上的 GCC 和 Mac OS X 上的 GCC 中进行了测试)。

我不得不根据平台使用宏来定义popen,因为在Windows上,函数是_popen,而在其他平台上函数名是popen(注意前者的下划线)。

#include <stdlib.h>
#include <stdio.h>

/* Change to whichever program you want */
//#define PROGRAM "program.exe --param1 --param2"
#define PROGRAM "dir"
#define CHUNK_LEN 1024

#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif

int main(int argc, char **argv) {

    /* Ensure that output of command does interfere with stdout */
    fflush(stdin);
    FILE *cmd_file = (FILE *) popen(PROGRAM, "r");
    if (!cmd_file) {
        printf("Error calling popen\n");
    }

    char *buf = (char *) malloc(CHUNK_LEN);
    long cmd_output_len = 0;
    int bytes_read = 0;
    do {
        bytes_read = fread(buf + cmd_output_len, sizeof(char), CHUNK_LEN, cmd_file);
        cmd_output_len += bytes_read;
        buf = (char *) realloc(buf, cmd_output_len + CHUNK_LEN);
    } while (bytes_read == CHUNK_LEN);

    /* Nul terminate string */
    *((char *) buf + cmd_output_len) = '\0';

    /* Close file pointer */
    pclose(cmd_file);

    /* Do stuff with buffer */
    printf("%s\n", buf);

    /* Free buffer */
    free(buf);

    return 0;
}
于 2012-08-03T15:20:57.057 回答
0

您可能想看看这个 Microsoft 示例代码。这对我很有用。 http://msdn.microsoft.com/en-us/library/ms682499%28VS.85%29.aspx

于 2012-08-03T06:53:20.057 回答
0

我使用了 CreateProcess,不幸的是,除了“仔细阅读 msdn”和“从简单到复杂”之外,我无法向您推荐其他任何东西。

至于可移植性——如果你直到现在还不需要使用一些跨平台的工具包,我不建议你仅仅因为这个而开始使用一个。我建议您编写一些“启动过程”包装器并以本机方式在每个平台上实现它。

于 2012-08-03T07:00:42.853 回答
0

最干净和最便携的方法是使用 GLib 的g_spawn_sync().

您可以在线找到文档。

gchar * std_out = NULL;
gchar * std_err = NULL;
gint exit_stat = 0;
const char *argv[] = {"--foo", "123", "--bar", "22323", NULL};

if(!g_spawn_sync (NULL, argv, NULL, NULL, NULL, NULL, &std_out, &std_err, &exit_stat, NULL)){
   fprintf(stderr, "Failed to spawn!\n");
};

/* std_out and std_err should now point to the respective output.*/
于 2012-08-06T16:09:52.540 回答