简体   繁体   English

如何在同一进程中执行命令

[英]How to execute commands in the same process

I made my own function to execute a command and save the result.我制作了自己的 function 来执行命令并保存结果。 The problem is the command is executed once and I can't execute several commands with the same "context".问题是命令执行一次,我无法执行具有相同“上下文”的多个命令。 For example.例如。 If I execute cd.. , the next command my cd.. will be ignored.如果我执行cd.. ,下一个命令 my cd..将被忽略。 This is my code:这是我的代码:

std::string executeCommand(const std::string& cmd)
{
    system((cmd + " > temp.txt").c_str());
    std::ifstream ifs("temp.txt");
    std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
    ifs.close(); // must close the inout stream so the file can be cleaned up
    return ret;
}

Can I have a sample with this feature?我可以提供具有此功能的样品吗?

Do you use Windows system? In Windows, you can interact with cmd through a Pipe.你用的是Windows系统吗?在Windows中,你可以通过一个Z2AB1F3F89382320875AZ1FDF60BE与cmd进行交互。

like this:像这样:

#define BUFFER_SIZE 131072 //128*1024‬
void work() {
    HANDLE hinRead, hinWrite, houtRead, houtWrite;

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = 0;
    sa.bInheritHandle = true;

    if (!CreatePipe(&hinRead, &hinWrite, &sa, 0)) {
        MessageBoxA(NULL, "Error CreatePipe", "Error", MB_ICONERROR);
    }
    if (!CreatePipe(&houtRead, &houtWrite, &sa, 0)) {
        MessageBoxA(NULL, "Error CreatePipe", "Error", MB_ICONERROR);
    }

    STARTUPINFOA si;
    ZeroMemory(&si, sizeof(si));
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdInput = hinRead;//redirect Input
    si.hStdOutput = si.hStdError = houtWrite;//redirect Output

    PROCESS_INFORMATION ProcessInformation;
    char cmdLine[256] = { 0 };
    GetSystemDirectoryA(cmdLine, sizeof(cmdLine));
    strcat(cmdLine, ("\\cmd.exe"));
    if (CreateProcessA(cmdLine, NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &ProcessInformation) == 0) {
        MessageBoxA(NULL, "Error CreateProcessA", "Error", MB_ICONERROR);
    }

    char* pbuff = new char[BUFFER_SIZE];
    DWORD dw;
    Sleep(100);//wait cmd start
    ReadFile(houtRead, pbuff, BUFFER_SIZE-1, &dw, NULL);
    pbuff[dw] = 0;
    printf(pbuff);//version info

    while (1) {
        char* p = pbuff;
        while ((*p = getchar()) != '\n') {
            ++p;
        }
        WriteFile(hinWrite, pbuff, p - pbuff + 1, &dw, 0);
        while (1) {
            ReadFile(houtRead, pbuff, BUFFER_SIZE - 1, &dw, NULL);
            pbuff[dw] = 0;
            printf("%s", pbuff);
            if (pbuff[dw - 1] == '>')break;
        }
    }
}

Pipe can read/write like a file. Pipe 可以像文件一样读/写。

In other systems, there is also something like pipe,but I'm not familiar with them.在其他系统中,也有类似管道的东西,但我对它们并不熟悉。

edit: another more clear example编辑:另一个更清楚的例子

int main() {

    HANDLE hinRead, hinWrite, houtRead, houtWrite;

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = 0;
    sa.bInheritHandle = true;

    if (!CreatePipe(&hinRead, &hinWrite, &sa, 0)) {
        MessageBoxA(NULL, "Error CreatePipe", "Error", MB_ICONERROR);
    }
    if (!CreatePipe(&houtRead, &houtWrite, &sa, 0)) {
        MessageBoxA(NULL, "Error CreatePipe", "Error", MB_ICONERROR);
    }

    STARTUPINFOA si;
    ZeroMemory(&si, sizeof(si));
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;//no window
    si.hStdInput = hinRead;//redirect Input
    si.hStdOutput = si.hStdError = houtWrite;//redirect Output

    PROCESS_INFORMATION pi;
    char cmdLine[256] = { 0 };
    GetSystemDirectoryA(cmdLine, sizeof(cmdLine));
    strcat(cmdLine, ("\\cmd.exe"));
    if (CreateProcessA(cmdLine, NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) == 0) {
        MessageBoxA(NULL, "Error CreateProcessA", "Error", MB_ICONERROR);
    }

    Sleep(100);//wait cmd start

    char* pbuff = new char[1024 * 128];
    DWORD dw;

    ReadFile(houtRead, pbuff, 1024 * 128, &dw, NULL), pbuff[dw] = 0, printf("%s", pbuff);//cmd version info


    WriteFile(hinWrite, "cd ..\n", 6, &dw, NULL);//send command to cmd.exe

    Sleep(100);//wait command execute and cmd outputs
    ReadFile(houtRead, pbuff, 1024 * 128, &dw, NULL), pbuff[dw] = 0, printf("%s", pbuff);


    WriteFile(hinWrite, "dir\n", 4, &dw, NULL);//another command
    Sleep(100);
    ReadFile(houtRead, pbuff, 1024 * 128, &dw, NULL), pbuff[dw] = 0, printf("%s", pbuff);

    delete[] pbuff;
    TerminateProcess(pi.hProcess, 0);//Terminate cmd.exe
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用管道在同一进程上执行多个shell命令时读死锁 - Read deadlock when using pipes to execute multiple shell commands on the same process 如何通过将每个命令分配给线程来在C ++中同时执行linux系统命令? - How can I execute linux system commands at same time in C++ by assigning each command to threads? 如何使用CreateProcess或ShellExecute执行管道命令 - How to use CreateProcess or ShellExecute to execute piped commands 如何在输入时执行命令? - How to execute commands WHILE taking input? 如何在 Windows 控制台中运行的 FarManager 中执行命令 - How to execute commands in FarManager running in Windows console 如何从附加的控制台执行命令 - How to execute commands from an attached console 如何使用SqlCommand :: Execute(或替代方法)从同一存储过程中“选择*”和“选择计数(*)”? - How does one process “select *” and “select count(*)” from same stored procedure using SqlCommand::Execute (or an alternative)? 在 C++ 的同一进程空间内执行外部可执行文件 - Execute an external executable within the same process space in C++ 如何在 C++ 中创建一个进程来执行 exe? - How to Create a process in c++ to execute exe? 如何通过捕获错误代码并采取适当措施来执行CMD命令 - How to execute CMD commands by catching the error code and taking appropriate actions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM