抑制 popen() 的输出

发布于 2025-01-06 18:28:40 字数 661 浏览 0 评论 0原文

有没有办法在不丢失 Wait() 的情况下抑制 popen() 的输出。

测试 1:

FILE * stream = NULL;
char buffer [120];

stream = popen ("ffmpeg -y -i test.amr -ar 16000 test.wav -v quiet", "r");

while (fgets (buffer, sizeof(buffer), stream))
{
}

pclose (stream);

测试 2:

FILE * stream = NULL;
char buffer [120];

stream = popen ("ffmpeg -y -i test.amr -ar 16000 test.wav -v quiet &> /dev/null", "r");

while (fgets (buffer, sizeof(buffer), stream))
{
}

pclose (stream);

测试 2 的问题是 pclose() 没有等待管道来完成处理。我不想每次做管道时都有一堆 FFMPEG 输出。

Is there a way to suppress the output from popen() without losing the Wait().

Test 1:

FILE * stream = NULL;
char buffer [120];

stream = popen ("ffmpeg -y -i test.amr -ar 16000 test.wav -v quiet", "r");

while (fgets (buffer, sizeof(buffer), stream))
{
}

pclose (stream);

Test 2:

FILE * stream = NULL;
char buffer [120];

stream = popen ("ffmpeg -y -i test.amr -ar 16000 test.wav -v quiet &> /dev/null", "r");

while (fgets (buffer, sizeof(buffer), stream))
{
}

pclose (stream);

The problem with Test 2 is that pclose() is not waiting for the pipe to finish processing. I don't want to have a bunch of FFMPEG output every time I have to do a pipe.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2025-01-13 18:28:41

仅当您想要向子进程发送数据或从子进程读取数据时,才应使用 popen()(这是一个异或;如果您想同时执行这两种操作,则必须设置自己建立连接)。

如果您不想这样做,请不要使用popen()

正如 jim mcnamara 准确解释,假设您将子项的输出重定向到/dev/null 创建管道后,重定向将关闭程序的管道输入,因此 popen() 读取零字节,这算作 EOF。它返回 - 没有更多内容可供它读取(如果可能有更多内容,它就不会收到 EOF)。

在这种情况下,请使用system();它会等待子进程完成 - 即使子进程的输出被重定向到 /dev/null 。在其他上下文中,可能适合使用较低级别的 fork() 和 exec*() 例程。

You should only use popen() when you want to send data to, or read data from, the child process (and that is an exclusive-or; if you want to do both, you have to set up the connection yourself).

If you don't want to do that, don't use popen().

As jim mcnamara accurately explained, given that you redirect the output of the child to /dev/null after the pipe is created, the redirection closes the pipe input to your program, so popen() gets zero bytes to read, which counts as EOF. And it returns - there is nothing more for it to read (if there might be more for it, it would not have received EOF).

In this context, use system(); it will wait for the child to finish - even when the output of the child is redirected to /dev/null. In other contexts, it might be appropriate to use the lower-level fork() and exec*() routines instead.

舟遥客 2025-01-13 18:28:41

输出到 /dev/null 意味着 popen (正在调用 read() )不会阻塞 stdout 的已关闭文件描述符。它立即返回。

您通过重定向( dup() )有效地关闭了 stdout,实际上它返回 EOF

output to /dev/null means that popen (which is calling read() ) does not block on a closed file descriptor for stdout. It returns right away.

You effectively closed stdout by redirecting it (dup() ), in reality it returns EOF

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文