![](/img/trans.png)
[英]Difference between this two codes(Why is my array taking extra space even if i gave a limit to it)
[英]Why is my pipe inserting an extra space between writes?
我有以下簡單程序。 它回顯行,直到收到一個帶有單獨q
。 然后退出。
// quitOnQ.cpp
int main()
{
string line;
while (line != "q")
{
cout << line << endl;
getline(cin, line);
}
return 0
}
當我自己啟動程序時,它會按預期運行。 但是,如果我從另一個程序啟動它,並使用匿名管道兩次寫入stdin,則會在第二次寫入的內容之前獲得一個額外的空間作為前綴。
j<enter>
->“ j”
q<enter>
-> [程序關閉]
q\\n
> [程序關閉]
j\\nq\\n
> [程序關閉]
j\\n
>“ j”
q\\n
>“ q” [程序保持打開狀態,請注意多余的空間]
為什么會這樣?
這是我用來寫到stdin的代碼:
#include <Windows.h>
#include <iostream>
#include <thread>
int main()
{
HANDLE hWriteIN, hReadIN;
SECURITY_ATTRIBUTES saPipe;
PROCESS_INFORMATION procInfo;
STARTUPINFO procSi;
DWORD dwWritten, dwRead;
saPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
saPipe.bInheritHandle = TRUE;
saPipe.lpSecurityDescriptor = NULL;
// child stdin pipe
CreatePipe(&hReadIN, &hWriteIN, &saPipe, 0);
SetHandleInformation(hWriteIN, HANDLE_FLAG_INHERIT, 0);
ZeroMemory(&procInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&procSi, sizeof(STARTUPINFO));
procSi.cb = sizeof(STARTUPINFO);
procSi.hStdInput = hReadIN;
procSi.dwFlags |= STARTF_USESTDHANDLES;
TCHAR args[] = TEXT("quitOnQ.exe");
CreateProcess(NULL, args, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &procSi, &procInfo);
this_thread::sleep_for(5s);
WriteFile(hWriteIN, "j\n", sizeof("j\n"), &dwWritten, NULL);
WriteFile(hWriteIN, "q\n", sizeof("q\n"), &dwWritten, NULL);
//WriteFile(hWriteIN, "j\nq\n", sizeof("j\nq\n"), &dwWritten, NULL);
this_thread::sleep_for(5s);
CloseHandle(hWriteIN);
return 0;
}
問題是您使用的sizeof()
錯誤。 編譯器將char
字符串文字視為以空const char[]
結尾的const char[]
數組。 在字符串文字上調用sizeof()
在大小中包含null終止符 ! sizeof("j\\n")
是3,而不是您期望的2。 空終止符是您多余空間的來源。 您應該使用strlen()
代替:
WriteFile(hWriteIN, "j\n", strlen("j\n"), &dwWritten, NULL);
WriteFile(hWriteIN, "q\n", strlen("q\n"), &dwWritten, NULL);
話雖如此,您應該改為將閱讀循環改為:
int main()
{
string line;
while (getline(cin, line))
{
if (line == "q") break;
cout << line << endl;
}
return 0
}
並且不要忘記關閉CreateProcess()
返回的句柄:
CloseHandle(procInfo.hThread);
CloseHandle(procInfo.hProcess);
sizeof("j\\n")
將返回字符串的長度+ 1,因為它以null終止。 這個多余的空間就是那個空字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.