c++ - WinSock 非阻塞 I/O

标签 c++ c sockets winapi pipe

我有一个 WSASocket,当连接时调用 CreateProcess 和服务器 cmd.exe,我想在进程 hStdInput 和套接字句柄之间实现一个管道来解析通过套接字发送的命令,一切似乎都运行顺利,除了因为当我运行“ping 127.0.0.1”之类的命令并且必须等待输出时,直到我通过套接字发送更多数据才显示任何内容,看来我的 ReadFile 调用正在阻止 hStdOut 处理程序发送任何内容。有没有什么办法解决这一问题?请不要被我的代码冒犯,我正在编写这个项目作为学习练习,任何帮助将不胜感激。

int syncShell(SOCKET *ConnectSocket) {
    int iResult = 0;
    printf("Spawning process\n");
    char Process[] = "C:\\Windows\\System32\\cmd.exe";
    STARTUPINFO sinfo;
    PROCESS_INFORMATION pinfo;
    memset(&sinfo, 0, sizeof(sinfo));
    sinfo.cb = sizeof(sinfo);
    sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);

    // create pipe for external commands
    SECURITY_ATTRIBUTES  saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL;
    HANDLE hReadPipe = NULL, hWritePipe = NULL;
    iResult = CreatePipe(&hReadPipe, &hWritePipe, &saAttr, DEFAULT_BUFLEN);
    if (iResult == 0) {
        printf("Pipe Error");
    }

    sinfo.hStdOutput = sinfo.hStdError = (HANDLE) *ConnectSocket;
    sinfo.hStdInput = hReadPipe;

    if (!CreateProcessA(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo)) {
        printf("CreateProcess failed (%d).\n", GetLastError());
    }

    // implement pipe logic
    char buf[DEFAULT_BUFLEN];
    DWORD len = 0;
    WSABUF DataBuf;

    while (1) {
        // causing the block?
        iResult = ReadFile((HANDLE) *ConnectSocket, buf, DEFAULT_BUFLEN, &len, NULL);
        if (iResult == 0) {
            printf("File Error or non-blocking");
        }
        else {
            printf("%d: %.*s\n", len, len, buf);
            WriteFile(hWritePipe, buf, len, NULL, NULL);
        }
        Sleep(1000);
    }

    WaitForSingleObject(pinfo.hProcess, INFINITE); // waits till proc finishes
    CloseHandle(pinfo.hProcess);
    CloseHandle(pinfo.hThread);
    printf("Process exited\n");

    return 0;
}

最佳答案

首先根据[ReadFile]文档:

For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or acceptfunction.

socket默认情况下使用 WSA_FLAG_OVERLAPPED 创建套接字句柄。 如果您传递 Overlapped 句柄并将 ReadFile 的最后一个参数设置为 NULL,您将收到错误代码 87(ERROR_INVALID_PARAMETER)。 使用重叠的示例:

OVERLAPPED oRead = { 0 };
oRead.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);  
iResult = ReadFile((HANDLE)ConnectSocket, buf, DEFAULT_BUFLEN, &len, &oRead);
if (!iResult && GetLastError() == ERROR_IO_PENDING)
{
    WaitForSingleObject(oRead.hEvent, INFINITE);
}
buf[oRead.InternalHigh] = 0;  //set string terminator for printf
printf("%s\n", buf);
WriteFile(hWritePipe1, buf, oRead.InternalHigh, NULL, NULL);

最好使用 recv()直接:

iResult = recv(ConnectSocket, buf, DEFAULT_BUFLEN, 0);
buf[iResult] = 0;  //set string terminator for printf
printf("%s\n", buf);
WriteFile(hWritePipe1, buf, iResult, NULL, NULL);

此外,重叠套接字可用于将 IO 重定向到子进程 您可以创建 2 个管道来与子进程通信:

iResult = CreatePipe(&hReadPipe1, &hWritePipe1, &saAttr, DEFAULT_BUFLEN);
if (iResult == 0) {
    printf("Pipe Error");
}
iResult = CreatePipe(&hReadPipe2, &hWritePipe2, &saAttr, DEFAULT_BUFLEN);
if (iResult == 0) {
    printf("Pipe Error");
} 

从子进程(cmd.exe)读取,并发送给客户端。

或者,

只需使用 WSASocket而不是socket ,并且不要指定 WSA_FLAG_OVERLAPPED。(推荐)

关于c++ - WinSock 非阻塞 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133452/

相关文章:

c++ - 捕获变量声明的异常

c++ - 添加十六进制值以获得结果十六进制

android - C++ 信号处理程序无法通知 Java 端

c - EAGAIN 后强制阻塞读取?

c - 在 c 结构的最后一个成员处填充

python - 套接字 python : recvfrom

java - 如何在java中使用TCP/IP将相同的数据从服务器发送到所有客户端?

C++: 奇怪的 "Request for member X of Y which is of non-class type Z"

C共享内存双 vector

java - 从一个线程写入套接字 channel 并从另一个线程选择