簡體   English   中英

c++ 如何寫入使用 createProcess 創建的進程

[英]c++ how to write to a process that was created with createProcess

我正在通過 createProcess 創建一個新的 Powershell 進程,並想向該 Powershell window 寫入命令並按 Enter。 這是我所擁有的:

 #include <cstdio>
    #include <windows.h>
    #include <tlhelp32.h>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
    
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
    
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        ZeroMemory(&pi, sizeof(pi));
    
        char myCommand[] = "cmd /c powershell.exe -NoExit";
    
        CreateProcess(NULL,      // No module name (use command line)
                      myCommand, // Command line
                      NULL,      // Process handle not inheritable
                      NULL,      // Thread handle not inheritable
                      FALSE,     // Set handle inheritance to FALSE
                      0,         // No creation flags
                      NULL,      // Use parent's environment block
                      NULL,      // Use parent's starting directory
                      &si,       // Pointer to STARTUPINFO structure
                      &pi);      // Pointer to PROCESS_INFORMATION structure
    
        Sleep(5000);
    
        string strMytestString("ls");
        cout << strMytestString.c_str();
    
        Sleep(2000);
    
        // ENTER key down
        keybd_event(VK_RETURN, 0x9C, 0, 0);
    
        // ENTER key up
        keybd_event(VK_RETURN, 0x9C, KEYEVENTF_KEYUP, 0);
        return 0;
    }

它打開 powershell 並將“ls”寫入其中並按 Enter 但 Powershell 不將其作為命令並且不執行“ls”而是將其寫為普通文本。 有沒有辦法讓 Powershell 執行我作為字符串傳遞給它的命令?

嘗試閱讀更多關於 STDIN、STDOUT 和 STDERR 的內容。

為了實現您的意圖,您必須將命令傳遞給子進程的 STDIN。

查看 MSDN 帖子使用重定向輸入和 Output 創建子進程,該帖子准確顯示了您的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM