我正在嘗試創建一個程序來創建多個進程,每個進程從控制檯讀取一行,然後執行其中的操作。我僅在有時閱讀一條線時遇到了getline(cin, temp)
的問題。輸入緩衝區已經加載了4行文本。C++ Getline並不總是在Linux中的多分叉進程中行
編輯:我需要使用fork,它創建多個進程(而不是線程),以便使用wait
,它等待第一個子進程完成,然後繼續。
#include <iostream>
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int childprog();
int main()
{
pid_t childpid;
for (int i = 0; i < 4; ++i)
{
if ((childpid = fork()) == 0) //Child process
{
childprog();
return 0;
}
}
if (childpid != 0) //If Parent
{
wait(0);
//Stuff
return 0;
}
}
int childprog()
{
string temp;
getline(cin, temp);
cout << temp << endl; //Actually do other stuff, just here for debugging
return 0;
}
雖然它應該打印出來:
string number one
string number two
string number three
string number four
它打印出:
string number one
string number two
string number three
或
(blank line)
string number one
string number two
在任何可能的位置的空行。
感謝您的幫助!
你可以提供[MCVE]嗎? –
好的,完成了。該程序是完全可運行的@πάνταῥεῖ – DDriggs00