gpt4 book ai didi

C运行外部程序出现错误

转载 作者:行者123 更新时间:2023-11-30 14:50:39 25 4
gpt4 key购买 nike

在我的 C 代码中,我想运行一个外部程序。为此,我使用 system() 函数,如下例所示:

system("/bin/myprog");

但我想检测我的外部程序是否有错误或无法正确退出。我怎样才能得到错误?

最佳答案

如果您想获取错误消息,那么您需要从外部程序捕获stderr。请注意,popen 会捕获 stdout,因此您需要使用 shell 构造 2>&1 进行重定向(幸运的是,popen 也运行外壳)。例如:

#define BUFF_SIZE 1024

int main()
{
char buffer[BUFF_SIZE];

FILE *p = popen("/bin/myprog 2>&1", "r");

while (fgets(buffer, BUFF_SIZE, p))
printf("Recieved: %s\n", buffer);

return 0;
}

编辑:要忽略 stdout 消息并仅获取 stderr 消息,然后使用:

FILE *p = popen("/bin/myprog 2>&1 1>/dev/null", "r");

关于C运行外部程序出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922662/

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