简体   繁体   English

如何让我的 C++ 代码知道从“system(cmd)”运行的命令是否失败?

[英]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()的返回值:

  • If it's zero, the command executed successfully and exited with a status of 0 .如果为零,则命令成功执行并以0状态退出。
  • If it's negative, there was a problem with system() itself, and you can't assume anything.如果它是否定的,则system()本身存在问题,您不能假设任何事情。
  • If it's positive, then you can use 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.

相关问题 我怎么知道我的代码是否已经编译? - How do I know whether my code has compiled? 如何在 Heroku 中运行我的 C++ 代码? - How do I run my C++ code in Heroku? 如何从命令行运行代码? - How do I run my code from the command line? C ++:如何从这段代码中创建这个形状? - C++: How do I make this shape from this code? 我怎么知道我的C ++字符串变量是否是数字 - How can I know whether my C++ string variable is a number or not 如何在 VS - Code (Windows) 中同时编译和运行我的 C++ 代码 - How do I compile and run my c++ code at the same time in VS - Code (Windows) 如何从命令行运行Eclipse IDE for C / C ++(我已经安装了它) - How do you run Eclipse IDE for C/C++ from the command line (I already installed it) 这是系统资源吗? (或如何知道是否需要删除指针)-在C ++中使用C - Is this a system resource? (or how do I know if I need to delete a pointer) - working with C in C++ 我如何从按Qt的按钮运行命令-C ++ - How do I run a command from a button press Qt - C++ probably 如何与SQL Server 2008建立稳定连接并用C ++编写我的第一个CRUD操作 - How do I make a stable connection with SQL Server 2008 and code my first CRUD operations in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM