父子之间的双向管道通信 [英] Two way pipe communication between parent and child
本文介绍了父子之间的双向管道通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用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);
}
推荐答案
程序几乎没有问题:
- 您没有在prog2.c中检查读取,写入和执行的返回值
- 您要发送的"7 + 5 + 11 =?\ n"字符串长度为10个字符,但只能期待4个字符(3 + 4 + 5甚至不是4个字符).
- 您发送的关闭"长度为3个字符,但不包含空终止符.
- 当您从
fd
中读取时,在两种情况下都不会获得以null终止的字符串,然后尝试对它进行printf
.这是一种不确定行为的快速方法.从任何文件描述符读取的缓冲区末尾都放置一个'\ 0'! - 特别地,
read
返回的内容非常重要,因为它告诉您读取了多少个字符.您永远都不应忽略read
的返回值(在某些情况下,与write
函数相同).
- You are not checking returned values of read, write and execle in prog2.c
- 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 ).
- Also "off" you are sending is 3 characters long but without including null termination.
- When you read from an
fd
you will in both cases not get null terminated string and then you are trying toprintf
it. It's a quick way to undefined behaviour. Put an '\0' after the end of buffer you read from any file descriptor! - Especially what
read
returns is very important as it tells you how many characters were read. You should never ignore returned value ofread
(in some cases it's the same withwrite
function).
下次还会提供一些程序输出,因为这将更容易提供帮助.
Next time also provide some output of your program as it will be easier to give some help.
这篇关于父子之间的双向管道通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文