首页 > 解决方案 > 我使用管道收到错误的文件描述符错误

问题描述

我的程序中出现错误的文件描述符错误,其中我的父进程从两个 .txt 文件中读取两个双精度值(文件的长度相同),如果第一个数字的绝对值 - 第二个数字大于 2,父进程将其发送给 pid3 子进程,否则将其发送给 pid2 子进程。

我想,我的管道有问题。


#include <sys/stat.h>  
#include <sys/unistd.h>  
#include <sys/types.h>
#include <fcntl.h>  
#include <stdlib.h>  
#include <sys/wait.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>  
#include <errno.h>
#include <string.h>
#include <time.h>
#include <math.h>

double atlag = 0;

double absz(double, double);

int main(int argc, char * argv[]) 
{
    FILE* be1;
    FILE* be2;
    // FILE* kiugro;
    // FILE* atlag;

    pid_t pid2, pid3;
    double x1, x2;
    int  p1[2], p2[2];

    be1 = fopen("be1.txt", "r");
    be2 = fopen("be2.txt", "r");

    if(pipe(p2) < 0)
    {
        syserr("pipe");
    }

    if(pipe(p1) < 0)
    {
        syserr("pipe");
    }

    if((pid2 = fork()) < 0)
    {
        syserr("fork");
    }

    if((pid3 = fork()) < 0)
    {
        syserr("fork");
    }

    if(pid2 == 0)
    {
        if(close(p1[1]) < 0)
        {
            syserr("close");
        }

        double temp;

        while(read(p1[0], &temp, sizeof(double)) == sizeof(double))
        {
            if(isnan(temp))
            {
                fclose(be2);
                break;
            }

            printf("a kulonbseg nkiugro: %lf\n", temp);
        }

        if(close(p1[0]) < 0)
        {
            syserr("close");
        }
    }

    if(pid3 == 0)
    {
        if(close(p2[1]) < 0)
        {
            syserr("close");
        }

        double temp;

        while(read(p2[0], &temp, sizeof(double)) == sizeof(double))
        {
            if(isnan(temp))
            {
                fclose(be1);
                break;
            }
            printf("a kulonbseg kiugro: %lf\n", temp);
        }

        if(close(p2[0]) < 0)
        {
            syserr("close");
        }
    }

    //parent process

    if(close(p2[0]) < 0)
    {
        syserr("close");
    }

    while(1)
    {
        if((fscanf(be1, "%lf", &x1) != EOF) && (fscanf(be2, "%lf", &x2) != EOF))
        {
            usleep(200);
            double temp = absz(x1, x2);

            if(temp > 2)
            {
                write(p2[1], &temp, sizeof(double));
            }
            else
            {
                write(p1[1], &temp, sizeof(double));
            }
        }
        else
        {
            double temp = NAN;

            write(p2[1], &temp, sizeof(double));
            write(p1[1], &temp, sizeof(double));

            break;
        }
    }

    if(close(p1[1]) < 0)
    {
        syserr("close");
    }

    if(close(p2[1]) < 0)
    {
        syserr("close");
    }

    waitpid(pid2, NULL, 0);
    waitpid(pid3, NULL, 0);

    return 0;
}

double absz(double x1, double x2)
{
    if((x1 - x2) >= 0)
    {
        return x1 - x2;
    }
    else
    {
        return (x1 - x2) * (-1);
    }
}

标签: cprocesspipeparent

解决方案


推荐阅读