[英]How do I make my c++ code know whether a command run from "system(cmd)" failed or not?
Let's assume I am running a unix command using system("foocmd param1")
on c++.假设我在 C++ 上使用system("foocmd param1")
运行 unix 命令。 If foocmd
returns "Invalid argument" back to the terminal via stderr, then how do I get my c++ code to know whether foocmd
failed?如果foocmd
通过 stderr 将“无效参数”返回到终端,那么我如何让我的 C++ 代码知道foocmd
是否失败?
Here is my attempted solution:这是我尝试的解决方案:
My assumption is that I should check whether anything got returned to stderr by calling the command.我的假设是我应该通过调用命令检查是否有任何东西返回到 stderr。 To do that, I tried switching over to popen.为此,我尝试切换到 popen。 Currently, this is the way I check.目前,这是我检查的方式。 I first output my stderr into a file.我首先将我的 stderr 输出到一个文件中。
sprintf(cmd, "foocmd param1 2>temp.txt");
system(cmd);
Then I check if temp.txt is empty or not.然后我检查 temp.txt 是否为空。
But there has to be a better way.但必须有更好的方法。 Can anyone lend me a hand?谁能帮我一把?
The usual way is to examine the return value of system()
:通常的方法是检查system()
的返回值:
0
.如果为零,则命令成功执行并以0
状态退出。system()
itself, and you can't assume anything.如果它是否定的,则system()
本身存在问题,您不能假设任何事情。WEXITSTATUS()
and related macros to find out how the process exited.如果是肯定的,那么您可以使用WEXITSTATUS()
和相关的宏来找出进程是如何退出的。 See the system(3)
man page for the full details.有关完整详细信息,请参阅system(3)
手册页。
Most of the time, you are only interested in whether the command says it succeeded:大多数时候,您只对命令是否成功感兴趣:
if (!system(cmd)) {
syslog(LOG_WARNING, "Command \"%s\" failed", cmd);
/* maybe some more error handling here */
goto err_return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.