从用户中读取整数并写入子管道,然后父管道从中读取

read integer from user and write into child pipe and then parent pipe read from it

本文关键字:管道 读取 然后 用户 整数      更新时间:2023-10-16

我正在尝试在管道中做简单的读/写但是它给了我错误

这是我的代码:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()  
{
    int fd[2],n,i,h;
    char buf[BUFSIZE];
    pipe(fd);   
    switch(fork())
    {   
        case -1 :printf("Fork Error");
            exit(0);
        case 0  :close(fd[0]);  
            printf("Enter N :");
            scanf("%d",&n);
            write(fd[1],&n,sizeof(n));
            close(fd[1]);
        case 1  :close(fd[1]);  
            n=read(fd[0],&h,sizeof(h));
            for(i=1;i<=h;i++)
            {
                if(i%2==1)
                {
                    write(1,&i,n);
                }
            }
            close(fd[0]);
    }
    exit(0);
}

在这段代码中:子节点的fd[0]指针被关闭并从子节点的fd[1]指针中写入,然后父节点从fd[1]指针中读取并将其存储在h变量中,然后变量i的值进入STDOUT_FILENO(1)并在标准输出

中显示输出输出:

kartik@ubuntu: ~/桌面/isp $

输入N:6

6: command not found

这里有几个问题:

  • 您在子进程中提示N,但是父进程是从终端接收输入的进程。所以当你输入"6"的时候,父进程已经退出了,你正在向shell输入这个值。将printfscanf移动到fork之前,您应该能够正确读取该值。
  • fork()从父级返回时,您的case 1将不会被输入,这似乎是您的意图。fork()将子进程的pid返回给父进程。因为特殊的init进程的pid是1,所以这永远不会为真。修改case 1:default,以处理父进程。
  • 你没有在你的开关箱结束时使用break。在C语言中,切换用例"失败",这意味着一旦一个用例的语句完成,它将继续运行下一个用例的语句。每个case末尾的break语句可以防止这种情况发生。

经过这些修改,你现在有了:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()
{
    int fd[2],n,i,h;
    pid_t pid;     // to capture the child pid
    char buf[BUFSIZE];
    // prompt for N before forking
    printf("Enter N :");
    scanf("%d",&n);
    pipe(fd);
    switch((pid=fork()))   // saving the child pid in case we want to use it later
    {
        case -1 :
            printf("Fork Error");
            exit(0);     // no break needed here because of exit
        case 0  :
            close(fd[0]);
            write(fd[1],&n,sizeof(n));
            close(fd[1]);
            break;       // end of case 0
        default :
            close(fd[1]);
            n=read(fd[0],&h,sizeof(h));
            printf("h=%dn",h);
            for(i=1;i<=h;i++)
            {
                if(i%2==1)
                {
                    //write(1,&i,n);
                    printf("%dn",i);
                }
            }
            close(fd[0]);
            break;      // end of default case
    }
    exit(0);
}

父进程需要等待它的子主题完成它的工作并将数据推送到管道中…

so add below line.

            wait(&status);