无法捕获CMD命令的最后结果? [英] The last result of CMD command can not be caught?

查看:156
本文介绍了无法捕获CMD命令的最后结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在命令行提示符中执行命令。该命令从c ++发送。如果我正在尝试执行3命令,则只执行2命令而第三个命令不会返回到c ++。

以下是我要执行的操作:

I am trying to execute a command in the command line prompt. This command is sent from c++. If i am trying to execute 3 command, only 2 is executed and the third is not returned to c++.
Here is what i am trying to execute:

wmic diskdrive get serialnumber& wmic cpu get ProcessorId& wmic os get SerialNumber& echo %username%





这是从CMD获取返回的代码片段我的编程:



Here is the code snippet of catching the return from CMD my prog:

cmd.append("2>&1");

    std::string data;
    FILE * stream;
    const int char_length= 256;
    char buffer[char_length];

    stream = popen(cmd.c_str(), "r");
    if (stream)
    {
        while (!feof(stream))
        if (fgets(buffer, char_length, stream) != NULL)
            data.append(buffer);
        pclose(stream);
     }
    return data;





返回的代码包含有关前3个命令的信息。我认为关于最后一个命令存在一些问题,但是当尝试交换命令时,最后一个命令也没有被程序捕获。



我是什么尝试过:



我通过让最后一个命令变得无用(我不需要)来解决这个问题,我做了它:



The returned code contain information about the first 3 command. I thought that there is some issue about the last command but when trying to swap the command the last command was not also caught by the programme.

What I have tried:

I have walked around the problem by making the last command a useless one (that i do not need), i made it:

echo




std::string cmd("wmic diskdrive get serialnumber& wmic cpu get ProcessorId& echo %username%& wmic os get SerialNumber& echo");





i认为必须有一个解决方案,提前感谢帮助



i think there must be a solution for this, thanks in advance for help

推荐答案

产生问题的行是

The line that creates the problem is
cmd.append("2>&1");

你忘了在输出重定向前插入一个空格:

You forgot to insert a space in front of the output redirection:

cmd.append(" 2>&1");



没有空格,最后一个命令是


Without the space the last command is

echo %username%2

,输出被重定向到标准输出。但这不起作用,因为输入已经来自 stdout ,因此重定向失败,并在 stderr 上显示错误消息现在你的代码没有抓住。



在命令提示符下尝试查看错误消息:

and the output is redirected to stdout. But that does not work because the input is already from stdout so that the redirection fails with an error message on stderr which is not catched by your code now.

Try it at a command prompt to see the error message:

echo %username%2>&1
The handle could not be duplicated during redirection of handle 1.


为什么你甚至要出来运行查询?直接自己运行查询。 WMI C ++应用程序示例(Windows) [ ^ ]
Why are you even shelling out to wmic to run the queries? Run the queries directly yourself. WMI C++ Application Examples (Windows)[^]


这篇关于无法捕获CMD命令的最后结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆