&1", "r"); 这一行中使用了 2>&1 而不是-6ren">
gpt4 book ai didi

运行系统命令和从控制台获取输出的混淆

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:34 25 4
gpt4 key购买 nike

在这里,我从某处获得了一个程序,用于从控制台读取系统调用的输出。但是为了获取错误消息,我在 fp = popen("ping 4.2.2.2 2>&1", "r"); 这一行中使用了 2>&1 而不是 fp = popen("ping 4.2.2.2", "r");

那么谁能给我解释一下上一行中 2>&1 的意义是什么。

这是我的代码。

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


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

FILE *fp;
int status;
char path[1035];

/* Open the command for reading. */
fp = popen("ping 4.2.2.2 2>&1", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}

/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}

/* close */
pclose(fp);

return 0;
}

最佳答案

0=标准输入 ; 1=标准输出2=标准错误

如果您执行 2>1,这会将所有 stderr 重定向到名为 1 的文件。要真正将 stderr 重定向到 stdout,您需要使用 2>&1&1 表示将句柄传递给 stdout

这个已经讨论过了here详细点。

关于运行系统命令和从控制台获取输出的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8651774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com