父母与孩子之间的双向pipe道沟通

我试图创build双向通信之间的父母和subprocess使用两个pipe道在C. prog1运行在child1我想从prog1读取3 + 4 + 5之后,发送一些事情与编写prog1,但我不能。 哪里错了?

/* 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中检查read,write和execle的返回值
  2. 您正在发送长度为10个字符的“7 + 5 + 11 =?\ n”字符串,但只需要4个字符(3 + 4 + 5甚至不是4个字符)。
  3. 你也发送“关闭”是3个字符长,但不包括空终止。
  4. 当你从一个fd读取你将在两种情况下不会得到空字符串,然后你试图printf它。 这是一个未定义行为的快速方法。 在从任何文件描述符读取的缓冲区结束之后放置一个'\ 0'!
  5. 特别是read返回是非常重要的,因为它告诉你读了多少个字符。 你永远不应该忽略read返回值(在某些情况下,它与write函数是一样的)。

下一次也提供一些你的程序的输出,因为它会更容易给一些帮助。

我没有按照你所有的设置管道的逻辑,所以我修改了一下,希望能澄清你的原文。 我应该注意到,无论出于什么原因,我从外部程序(prog1)的角度来命名fd_in和fd_out(例如,fd_out是prog1正在写入的地方,fd_in是prog1正在读取的地方)。

这里是我的prog3.c的内容:

 ... #define READ_END 0 #define WRITE_END 1 void ERR_SYS(const char *msg); int main(void) { char buff[15]; char *msg = "hello"; int fd_out[2]; int fd_in[2]; int nbytes; pid_t childpid; if(pipe(fd_out) < 0 || pipe(fd_in) < 0) { ERR_SYS("fail_pipe"); } if((childpid = fork()) < 0) { ERR_SYS("fail_fork"); } if(childpid==0) { //child //connect the write end of fd_out to stdout dup2(fd_out[WRITE_END], STDOUT_FILENO); close(fd_out[WRITE_END]); //connect the read end of fd_in to stdin dup2(fd_in[READ_END], STDIN_FILENO); close(fd_in[READ_END]); //the exec'd prog1 will inherit the streams execlp("./prog1", "prog1", NULL); //TODO: check return } else { //parent nbytes = write(fd_in[WRITE_END], msg, strlen(msg)); //TODO: handle any errors from write nbytes = read(fd_out[READ_END],buff,sizeof(buff)-1); //TODO: handle any errors from read buff[nbytes] = '\0'; printf("contents of buff::%s",buff); } return 0; } void ERR_SYS(const char *msg) { perror(msg); exit(EXIT_FAILURE); } 

这里是我的prog1.c的内容

 int main(void){ char buff[15]; int nbytes; nbytes = read(STDIN_FILENO, buff, sizeof(buff)-1); buff[nbytes] = '\0'; printf("%s world\n", buff); return 0; 

}