简体   繁体   English

使用 CreateProcess() 创建的 cmd.exe 不从 WriteFile() 读取

[英]cmd.exe created with CreateProcess() doesn't read from WriteFile()

I have created a child process with CreateProcess().我用 CreateProcess() 创建了一个子进程。 an instance of cmd.exe. cmd.exe 的一个实例。 The first command is passed in the creation of the process and the second is passed through WriteFile(), after the process is created.第一个命令在进程创建时传递,第二个命令在进程创建后通过 WriteFile() 传递。 The first job is done and the second isn't and I don't know the reason why.第一份工作完成,第二份没有完成,我不知道为什么。 Please help请帮忙

The code for creating the process is:创建流程的代码是:

PROCESS_INFORMATION _info;
char cmd[1024];
strcpy(cmd,"C:\\Windows\\system32\\cmd.exe /k echo 1");

    HANDLE _stdin_rd = NULL;
    HANDLE _stdin_wr = NULL;
    HANDLE _stdout_rd = NULL;
    HANDLE _stdout_wr = NULL;
    BOOL br;
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
    br = CreatePipe(&_stdin_rd, &_stdin_wr, &sa, 0);
    br = SetHandleInformation(_stdin_wr, HANDLE_FLAG_INHERIT, 0);
    br = CreatePipe(&_stdout_rd, &_stdout_wr, &sa, 0);
    br = SetHandleInformation(_stdout_rd, HANDLE_FLAG_INHERIT, 0);
    STARTUPINFO si;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    ZeroMemory(&_info, sizeof(PROCESS_INFORMATION));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags |= STARTF_USESTDHANDLES;
    si.hStdInput = _stdin_rd;
    si.hStdOutput = _stdout_wr;
    si.hStdError = _stdout_wr;
    br = CreateProcess(0, cmd,0,0,TRUE,CREATE_NO_WINDOW,0,0,&si,&_info);
    CloseHandle(_stdout_wr);
    CloseHandle(_stdin_rd);
    CloseHandle(_info.hProcess);
    CloseHandle(_info.hThread);
    printf("process created...\n");

    Sleep(320);
    printf("waited\n\n");

The code for communicating with the process is:与进程通信的代码是:

    char bufy[10240];
    char kom[1024];
    long unsigned int prt, ovs=0;
    for(int i=2;i<10;++i){
        if(!ReadFile(_stdout_rd,bufy+ovs,10240-ovs,&prt,0)){
            printf("   ERROR=%d\n",GetLastError());
            break;
        }
        ovs+=prt;
        printf("respond: ");
        bufy[ovs]=0;
        printf("%s\n",bufy);

        sprintf(kom,"/k echo %d",i);
        BOOL odgw = WriteFile(_stdin_wr,kom,strlen(kom),0,0);
        printf("sent(%s): %s\n",odgw?"TRUE":"FALSE",kom);
    }

return 0;

All I get on the output of my program is:我得到的程序输出是:

process created...
waited

respond: 1

D:\>
sent(TRUE): /k echo 2

I found the mistake.我发现了错误。 Commands to be passed afterwards should not begin with /k and should end with \\n .之后传递的命令不应以/k开头,而应以\\n结尾。 Then the program works.然后程序运行。 Also, in the creation of the process, there may not be anything after /k , the program will still work.另外,在创建过程中, /k之后可能没有任何内容,程序仍然可以运行。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM