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

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

我正在尝试在管道中做简单的 read/write 但它给了我错误

这是我的代码:

#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);
}

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

上显示输出

输出:

kartik@ubuntu:~/Desktop/isp$

Enter N :6

6: command not found

这里有几个问题:

  • 您在 child 进程中提示输入 N,但是 parent 进程是从终端接收输入的进程。因此,当您输入“6”时,parent 进程已经退出,您正在向 shell 输入该值。将 printfscanf 移动到 fork 之前,您应该能够正确读取该值。
  • 如果 parent fork() returns,您的 case 1 将不会被输入,这似乎是您的意图。 fork() returns child 的 pid 到 parent。因为特殊 init 进程的 pid 为 1,所以这永远不会成立。将 case 1: 更改为 default 以处理 parent 过程。
  • 您没有在 switch case 的末尾使用 break。在 C 语言中,switch cases "fall through" 意味着一旦一个 case 的语句完成,它将继续 运行 下一个 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=%d\n",h);
            for(i=1;i<=h;i++)
            {
                if(i%2==1)
                {
                    //write(1,&i,n);
                    printf("%d\n",i);
                }
            }
            close(fd[0]);
            break;      // end of default case
    }
    exit(0);
}

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

所以添加下面一行。

            wait(&status);