【发布时间】:2017-02-16 05:08:22
【问题描述】:
我正在尝试编写一个程序来创建多个进程,每个进程从控制台中读取一行,然后用它做一些事情。我在使用getline(cin, temp) 时遇到问题,只是有时会读一行。输入缓冲区已经加载了 4 行文本。
编辑:我需要使用 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
在任何可能的位置都有空行。
感谢您的帮助!
【问题讨论】:
-
你能提供一个minimal reproducible example吗?
-
好的,完成。该程序完全可运行@πάνταῥεῖ