C++ 为什么这段代码在到达管道时停止运行?

C++ 为什么这段代码在到达管道时停止运行?,c++,fork,pipe,C++,Fork,Pipe,当这个程序运行时,它通过父程序中的循环,然后在写入管道时切换到子程序。在子进程中,读取的管道只会导致程序停止 当前示例输出: 父项4741 14087(仅当预计还有5行时才使用此行) 预期输出(随机生成的数字): 家长474114087 儿童474047082 家长474111345 儿童474099017 家长474196744 儿童474098653 (当给定变量3且最后一个数字是随机生成的数字时) #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 使用名称空间std; int

当这个程序运行时,它通过父程序中的循环,然后在写入管道时切换到子程序。在子进程中,读取的管道只会导致程序停止

当前示例输出:

父项4741 14087(仅当预计还有5行时才使用此行)

预期输出(随机生成的数字):

家长474114087

儿童474047082

家长474111345

儿童474099017

家长474196744

儿童474098653 (当给定变量3且最后一个数字是随机生成的数字时)

#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[]){
int pid=fork(),temp,randNum,count,pipeName[2],pipeName2[2];
弦变换器;
管道(管道名称);
conver=argv[1];
temp=atoi(conver.c_str());
字符字母;
如果(pid==0){//child
srand((无符号)时间(NULL)*getpid());
//关闭未使用的管道
关闭(管道名称2[1]);
关闭(pipeName[0]);
//循环以在进程之间切换

对于(int i=0;i而言,您的主要错误是在初始化管道之前初始化
fork()
。因此,父级和子级都有自己的私有(未通过fd继承共享)管道对,名为
pipeName
,只有父级使用管道fds初始化
pipeName2

对于家长来说,在
pipeName[0]
后面根本没有数据可读取。对于孩子来说……谁知道它在
pipeName2[1]
中写入的fd是什么呢?如果幸运的话,EBADF失败了


因此,首先是两次
pipe()
,然后是
fork()
,看看这是否能改善情况。

我闻到os161和操作系统分配的味道,它解决了问题,但现在它转到了写语句,然后程序又结束了。对此有什么想法吗?@Dean,很难说没有演示代码的问题。即兴说,我想知道你是不是因为试图
阅读而崩溃了()
20个字节放入一个字符的缓冲区。。。
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <ctime>
using namespace std;

int main (int argc, char *argv[]) {
    int pid = fork(), temp, randNum, count, pipeName[2], pipeName2[2];
    string conver;
    pipe(pipeName);
    conver = argv[1];
    temp = atoi(conver.c_str());
    char letter;


    if (pid == 0) { //child
        srand((unsigned)time(NULL) * getpid() );
        //closing unused pipes
        close(pipeName2[1]);
        close(pipeName[0]);
        //loop to switch between processes
        for(int i=0; i<temp; i++) {
            count = read(pipeName2[0], &letter, 20);
            randNum = rand();
            cout << "Child " << getpid() << " " << randNum << endl;
            write(pipeName[1], "x", 1);
        }
        close(pipeName2[0]);
        close(pipeName[1]);
    }
    else { //parent
        srand((unsigned)time(NULL) * getpid() );
        pipe(pipeName2);
        //closing unused pipes
        close(pipeName2[0]);
        close(pipeName[1]);
        //loop to switch between processes
        for(int i=0; i<temp; i++) {
            if(i != 0)
                count = read(pipeName[0], &letter, 20);
            randNum = rand();
            cout << "Parent " << getpid() << " " << randNum << endl;
            write(pipeName2[1], "x", 1);
        }
        close(pipeName[0]);
        close(pipeName2[1]);
    }
}