管道无法读取Enter键(C,Linux)

时间:2015-11-12 16:01:32

标签: c linux

我是初学者,我正在C,Linux中编写一个双向通信程序,用于作业提交。但是,我已经测试并发现"进入"密钥不能通过管道读取,因为它包含0字节。如果在键入普通字符之前意外按下回车键,则2个屏幕将变为死锁且无法通信。我尝试了getchar()或检查byte = 0,但我不知道我应该把命令放在哪个位置才能使它工作。有任何想法吗?感谢

(下面是发件人,我希望程序可以发送和接收消息)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int main()
{ char  pipename1[] = "/tmp/pipe1"; /* pathname of the named pipe */
char    buf1[80];

char  pipename2[] = "/tmp/pipe2"; /* pathname of the named pipe */
char    buf2[80];

int i, n1,n2, fd1, fd2;

mkfifo(pipename1,0666);
printf("Please run receiver in other putty. \n");

fd1 = open(pipename1,O_WRONLY);
fd2 = open(pipename2,O_RDONLY);

while(1){ 

printf("Please enter a message. <To check message, press Enter>\n");


n1 = read(STDIN_FILENO,buf1,80); /* read a line */
   if (n1 <= 0) break; 
   buf1[--n1] = 0;
   write(fd1,buf1,n1); /* send the string */



while ((n2 = read(fd2,buf2,80)) > 0) { /* read from pipe */ 
buf2[n2] = 0;
printf("\n <player2> [%s] \n",buf2,n2);
break;}


}

close(fd1);
close(fd2);
unlink(pipename1);
unlink(pipename2);
exit(0); }

(已编辑)实际上我创建了另一端来读取msg,代码在

之下
int main()
{  char pipename1[] = "/tmp/pipe1"; /* pathname of the named pipe */
char    buf1[80];

char  pipename2[] = "/tmp/pipe2"; /* pathname of the named pipe */
char    buf2[80];
int i, n1,n2, fd1, fd2;

mkfifo(pipename2,0666); /* make file with the file name defined in pipename1, 0666 is permission every one can read & write */
printf("Please run receiver programme in another browser\n");

fd1 = open(pipename1,O_RDWR);
fd2 = open(pipename2,O_RDWR);

while(1){ 
printf("<Please enter a message.\n");

n2 = read(STDIN_FILENO,buf2,80); /* read a line */
if (n2 <= 0) break; 
buf2[--n2] = 0;
write(fd2,buf2,n2); /* send the string */


while ((n1 = read(fd1,buf1,80)) > 0) { /* read from pipe */
buf1[n1] = 0;
printf("\n <player1>[%s]\n",buf1,n1);
break;}
}       
close(fd1);
close(fd2);
exit(0);
}

1 个答案:

答案 0 :(得分:1)

问题是你写入管道(使用fd1)但你没有读取。相反,你打开一个完全不相关的文件并尝试从中读取。

文件系统中的命名管道是由mkfifo初始化的单个文件,并且与所有其他管道一样,它具有写端和读端,并且通过打开相同的文件来访问两端