为什么fork进程似乎提前结束了我的程序



我正试图在C++中使用子进程,并使用管道在它们之间进行通信,我认为我的想法是正确的,但在do-while循环结束进程后遇到了一个奇怪的错误。为什么会发生这种情况,我能做些什么来解决它。我的一个高级检查是我的测试,如果我在那一行之后删除所有内容,它就会显示出来,但不是其他情况。我该怎么办?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main()
{
string password;
string discovery;
int fd[2]; // One for the child to write to the parent
//int reversefd[2]; // Another for the parent to write to the child
if (pipe(fd) < 0) {
cout << "Cannot create pipe";
exit(1);
}
//if(pipe(reversefd)<0){
//cout <<"Cannot create pipe";
//exit(1);
//}
pid_t chPl;
cout << "Enter the password(no spaces): ";
do {
cin >> password;
if (password.length() > 20) {
cout << "Enter a password with less than 20 characters: ";
}
} while (password.length() > 20);
cout << "check";
close(fd[0]);
dup2(fd[1], 1);
cout << password << endl;
chPl = fork();
if (chPl < 0) //Nothing was created
{
cout << "Unable to make child";
exit(2);
}
else if (chPl == 0) //In the child process
{
string attempt;
close(fd[1]);
dup2(fd[0], 0);
cin >> attempt;
cout << attempt;
}
else // Parent
{
wait(0);
cout << "parent function started again";
}
}

我发现了问题,我过早地关闭了它,导致它很快失败,我重新排列了代码,将close语句置于等待之上。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;
int main(){
string password;
string discovery;
int fd[2]; // One for the child to write to the parent
//int reversefd[2]; // Another for the parent to write to the child
if(pipe(fd)<0){
cout <<"Cannot create pipe";
exit(1);
}
//if(pipe(reversefd)<0){
//cout <<"Cannot create pipe";
//exit(1);
//}
pid_t chPl;

cout << "Enter the password(no spaces): ";
do {
cin >> password;
if(password.length() > 20){
cout << "Enter a password with less than 20 characters: ";
}
}
while(password.length() > 20);

chPl=fork();
if(chPl<0) //Nothing was created
{
cout << "Unable to make child";
exit(2);
}
else if(chPl==0) //In the child process
{
string attempt;
close(fd[1]);
dup2(fd[0], 0);
cin >> attempt;
cout << attempt;
}
else // Parent
{
cout << "check";
close(fd[0]);
dup2(fd[1], 1);
cout << password<< endl;
wait(0);
cout << "parent function started again";
}
}

最新更新