在父进程中从.txt中读取数字,并使用管道将其发送到子进程并进行写入

问题描述 投票:0回答:1

我正在尝试从父母向孩子发送双精度数字,但它只打印第一个数字,然后停止。

这是我的代码:


#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>

int main()
{
    pid_t pid;
    int pip[2];
    int fd, n;
    double x1;
    double x2;

    pipe(pip);

    pid = fork();

    fd = open("numbers.txt", O_RDONLY);

    if(pid == 0)
    {
        close(pip[1]);

        read(pip[0], &x2, sizeof(double));

        printf("%lf\n", x2);

        close(pip[0]);
    }
    else
    {
        close(pip[0]);
        n = read(fd, &x1, sizeof(double));

        while(n)
        {
            write(pip[1], &x1, sizeof(double));
        }

        close(pip[1]);

        waitpid(pid, NULL, 0);
    }

    return 0;
}

当我尝试读写时,我正在关闭管道,另一个问题是,它打印的是0.000000,而不是数字的实际值。

c process pipe parent
1个回答
1
投票

仅先打印然后停止。

© www.soinside.com 2019 - 2024. All rights reserved.