父子之间的双向管道通信 [英] Two way pipe communication between parent and child

查看:168
本文介绍了父子之间的双向管道通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C中的2条管道在父进程和子进程之间创建双向通信.在child1中运行的prog1 我想从prog1中读取3 + 4 + 5,然后通过写操作将某些内容发送到prog1中,但是我做不到. 哪里错了?

I'm trying to create two-way communication between parent and child processes using 2 pipes in C.the prog1 running in child1 I want to read 3+4+5 from prog1 after that send something to prog1 with write but I could not. Where is the wrong?

/* prog1.c */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void
main(void){
    int FD;
unsigned int buf;
char buf[15];

printf("7+5+11=?\n");
FD=read(0,buf,10);
if(FD<0){
    perror("FAIL\n");
exit(EXIT_FAILURE);
}
     printf("TAKED:%s\n",buf);
}

prog2.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
void ERR_SYS(const char *msg);
int
main(void){
    char buf[15];
    int pipe1[2];
    int pipe2[2];
    pid_t childpid;

    memset(buf,'\0',14);

    if(pipe(pipe1) < 0 || pipe(pipe2) < 0)
     ERR_SYS("fail_pipe");

    if((childpid = fork()) < 0)
     ERR_SYS("fail_fork");

    if(childpid==0)
    {
      dup2(pipe2[1],1);
          dup2(pipe1[0],0);
      close(pipe1[1]);
          close(pipe2[0]);
      close(pipe2[1]);
      close(pipe1[0]);
          //close(1);
          //close(0);
      execle("./prog1",NULL,NULL,NULL);
    }else{

     close(pipe1[0]);
     close(pipe2[1]);
     read(pipe2[0],buf,4); /*I hope to read 3+4+5*/
     printf("BuF::%s\n",buf);
     write(pipe1[1],"off",3);/*send {off}*/
     wait(NULL);
    }
 return 0;
 }

 void 
 ERR_SYS(const char *msg)
 {
     perror(msg);
     exit(EXIT_FAILURE);
 }

推荐答案

程序几乎没有问题:

  1. 您没有在prog2.c中检查读取,写入和执行的返回值
  2. 您要发送的"7 + 5 + 11 =?\ n"字符串长度为10个字符,但只能期待4个字符(3 + 4 + 5甚至不是4个字符).
  3. 您发送的关闭"长度为3个字符,但不包含空终止符.
  4. 当您从fd中读取时,在两种情况下都不会获得以null终止的字符串,然后尝试对它进行printf.这是一种不确定行为的快速方法.从任何文件描述符读取的缓冲区末尾都放置一个'\ 0'!
  5. 特别地,read返回的内容非常重要,因为它告诉您读取了多少个字符.您永远都不应忽略read的返回值(在某些情况下,与write函数相同).
  1. You are not checking returned values of read, write and execle in prog2.c
  2. You are sending "7+5+11=?\n" string which is 10 characters long but only expecting 4 characters ( 3+4+5 is not even four characters ).
  3. Also "off" you are sending is 3 characters long but without including null termination.
  4. When you read from an fd you will in both cases not get null terminated string and then you are trying to printf it. It's a quick way to undefined behaviour. Put an '\0' after the end of buffer you read from any file descriptor!
  5. Especially what read returns is very important as it tells you how many characters were read. You should never ignore returned value of read (in some cases it's the same with write function).

下次还会提供一些程序输出,因为这将更容易提供帮助.

Next time also provide some output of your program as it will be easier to give some help.

这篇关于父子之间的双向管道通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆