1

您好,我在网上看到了一些解决方案,基本上都是创建一个文件,但是我想将它们存储在一个 char 数组中。速度对我来说真的很重要,我不想花时间在硬盘上工作。所以popen()对我来说不是一个真正的解决方案。

4

5 回答 5

6

这是一个工作代码片段:

char bash_cmd[256] = "ls -l";
char buffer[1000];
FILE *pipe;
int len; 

pipe = popen(bash_cmd, "r");

if (NULL == pipe) {
    perror("pipe");
    exit(1);
} 

fgets(buffer, sizeof(buffer), pipe);

len = strlen(buffer);
buffer[len-1] = '\0'; 

pclose(pipe);
于 2013-01-18T09:44:36.110 回答
2

If you would read the manpage of popen, you would notice the following:

The popen() function opens a process by creating a pipe, forking, and invoking the shell. [...] The return value from popen() is a normal standard I/O stream in all respects save that it must be closed with pclose() rather than fclose(3). [...] reading from a "popened" stream reads the command's standard output, and the command's standard input is the same as that of the process that called popen().

(emphasis mine)

As you can see, a call to popen results in the stdout of the command being piped into your program through an I/O stream, which has nothing to do with disk I/O at all, but rather with interprocess communication managed by the operating system.

(As a sidenote: It's generally a good idea to rely on the basic functionality of the operating system, within reason, to solve common problems. And since popen is part of POSIX.1-2001 you can rely on it to be available on all standards compliant operarting systems, even windows)

EDIT: if you want to know more, read this: http://linux.die.net/man/3/popen

于 2013-01-18T08:28:37.683 回答
2

永远不要忘记 Knuth 所说的“过早的优化是万恶之源”。在重要之前不要担心性能,然后在做任何事情之前进行测量。除极少数情况外,您的时间价值远高于程序运行的成本。

Jon Bentley 的“编写高效的程序”(遗憾的是已绝版,在他的“编程珍珠”一章中有总结)详细讨论了如何使程序运行得更快(如果值得的话);并且仅作为最后一项措施,为了挤出最后可能的 2% 性能(在将运行时间减少一半之后),它建议使用您建议的更改。引用的书包含一些非常有趣的关于“性能优化”的战争故事,这些故事完全是浪费(优化从未使用过的代码,优化代码在操作系统转动拇指时运行,......)。

于 2013-01-20T02:16:48.487 回答
0

如果速度对您很重要,您可以编写自己的 popen 版本。

这可能是有道理的,因为 popen() - 创建一个管道 - 分叉 - 执行外壳(非常昂贵!) - 外壳比创建管道,分叉,执行你的程序

您的定制版本可以将过程减少到: - 创建管道 - 分叉 - 执行您的程序

您甚至可以扩展 popen 来分别控制命令 STDOUT、STDERR 和 STDIN。我写了这样一个例程,见https://github.com/rockdaboot/mget/blob/master/libmget/pipe.c 是 GPL 的。

您使用 FILE 指针调用 mget_popen3() 或使用文件描述符调用 mget_fd_popen3()。至少,它应该让你知道如何去做。

于 2013-01-18T09:00:46.510 回答
-2

您介意拥有多个 C 程序吗?如果您不介意,您可以使用命令行参数。在第一个 C 程序中,您可以执行以下操作

system("YourCommand | SecondProgram");

SecondProgram将是您将要编写的第二个 C 程序的“可执行文件”。在第二个 C 程序中,您可以将命令的输出YourCommand作为命令行参数接收到SecondProgram. 为此,您可以开始第二个 C 程序的 main(),如下所示

main(int argc,char *argv[])

该数组argv将具有 的输出,YourCommand并且argc将包含数组中的元素数argv

于 2013-01-18T07:09:40.200 回答