简体   繁体   English

C ++ ReadFile,CreateProcess,管道标准输出重定向,输出翻倍

[英]C++ ReadFile, CreateProcess, Pipe Stdout redirection, doubled Output

i have this piece of code : 我有这段代码:

        for (;;) {
            BOOL ReadSuccess = ReadFile(rdPipe, StdOutBuffer, 8192, &dwRead, NULL);

            if (strlen(StdOutBuffer) <= 0) {
                Sleep(100);
                send(sock, RECIEVE_BREAK, strlen(RECIEVE_BREAK), 0);
                break;
            }

            else if (!ReadSuccess || dwRead == 0) {
                Sleep(100);
                send(sock, RECIEVE_BREAK, strlen(RECIEVE_BREAK), 0);
                break;
            }

            else {
                send(sock, StdOutBuffer, strlen(StdOutBuffer), 0);
            }

            cout << StdOutBuffer << endl;
            cout << "\n\n\n\n";
        }

And i have problem with doubled output in my StdOutBuffer, for example, when i call "tasklist" i've got some parts twice. 而且我在StdOutBuffer中输出翻倍时遇到问题,例如,当我调用“任务列表”时,我得到了两次零件。

Dont u someone know where can be problem? 你不知道哪里可能有问题吗?

The function ReadFile() doesn't read a null terminated c-string, but a block of (here 8192) chars without any guarantee to have a null terminator. 函数ReadFile()不会读取以null结尾的c字符串,但是会读取(此处为8192)个字符的块,而不能保证具有null终止符。

Therefore, calling strlen(StdOutBuffer) is not guaranteed to give any useful result. 因此,不能保证调用strlen(StdOutBuffer)会给出任何有用的结果。 You should rather rely on dwRead instead. 您应该改为依靠dwRead If you read text data that might be not null terminated (in the file or, as it seems, via the pipe), you should add it yourself: 如果读取的文本数据可能不是以null结尾的(在文件中,或者看起来是通过管道),则应自己添加:

 StdOutBuffer[dwLen] = '\0'; 

This works even if the read fails, because the first thing ReadFile() does is to set the length to 0. Note that your buffer should then have a size of at least 8192+1 char. 即使读取失败,该方法仍然有效,因为ReadFile()所做的第一件事就是将长度设置为0。请注意,缓冲区的大小应至少为8192 + 1个字符。

Why do you get the error ? 为什么会出现错误? Suppose you receive a full line of data, and that fortunately, it includes some null terminator. 假设您收到一整行数据,幸运的是,它包含一些空终止符。 You'd then process it. 然后,您将对其进行处理。 Suppose now that in the next iteration you'd only receive a couple of chars (eg just a newline): the remaining of the buffer would not overwritten, and as you'd not have a null terminator at the end of the new bytes read, strlen() would cause to think there is more data to process than there is; 现在假设在下一次迭代中,您将只收到几个字符(例如,仅换行符):缓冲区的其余部分将不会被覆盖,并且因为在读取的新字节的末尾没有空终止符, strlen()会导致认为有更多数据要处理; some data would be processed a second time. 一些数据将被第二次处理。

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

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