c - 我使用管道收到错误的文件描述符错误
问题描述
我的程序中出现错误的文件描述符错误,其中我的父进程从两个 .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);
}
}
解决方案
推荐阅读
- python - win32com 在没有时区转换的情况下将 Python 日期时间传递给 Excel
- php - 如何使用加密密码登录php
- sql - 查看 SQL Server Integration Services (SSIS) 转换的 SQL
- python - 如何使用 BeautifulSoup 获取嵌套在 TD 中的 DIV 内部的链接
- r - 如何在使用“聚合”降低分辨率后合并原点差异较小的光栅图块
- postgresql - 无法在 GeoServer 中创建数据存储
- android-studio - import kotlinx.android.synthetic.main.activity_main.* kotlinx 中的错误
- python - 无法将文章内容附加到列表
- python - 使用apply时,如何在整个事情超时之前保存使用pandas列的API调用的结果?
- python - 有没有办法使用 Python 将图像从 API 导入 PowerBI 仪表板