linux 命名管道 聊天程序 请教大神!!!!!!!!!!!!!!!!!!!!!!
求纠错!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!实在是不知道哪里错了,就是不能读取管道的内容。
程序一:
//this is p1
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<sys/select.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int rfd,wfd,len;
char str[256];
memset(str,0,256);
/*-------make fifo----------------*/
printf("making fifo......\n");
unlink("fifo1");
if(mkfifo("fifo1",0777)!=0)
{
perror("mkfifo1 failed\n");
exit(1);
}
/*-----------open file descriptor-------*/
printf("opennig file descriptor..........\n");
wfd=open("fifo1",O_NONBLOCK,O_WRONLY);
printf("write_fd is ok......\n");
while((rfd=open("fifo2",O_NONBLOCK,O_RDONLY))==-1)
{
sleep(1);
printf("no response,can\'t get read_fd....\n");
}
printf("read_fd is ok...........\n");
if(rfd<=0||wfd<=0)
{
perror("open fifo failed!\n");
exit(1);
}
/*----------intercourse part------------*/
printf("this is p1\n");
printf("-------------------------\n");
while(1)
{
printf("p1:");
fgets(str,256,stdin);
str[strlen(str)-1]='\0';
if(strncmp(str,"88",2)==0)
{
close(wfd);
unlink("fifo1");
close(rfd);
exit(0);
}
printf("sending messages to p2.....\n");
sleep(1);
write(wfd,str,strlen(str));
len=read(rfd,str,sizeof(str));
if(len>0)
{
str[len]='\0';
printf("p2:%s\n",str);
}
else
{
sleep(1);
printf("nothing got from p2!\n");
}
}
}
然后这是程序二:
//this is p2
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<sys/select.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int rfd,wfd,len;
char str[256];
memset(str,0,256);
/*-------make fifo----------------*/
printf("making fifo............\n");
unlink("fifo2");
if(mkfifo("fifo2",0777)!=0)
{
perror("mkfifo2 failed\n");
exit(1);
}
/*-----------open file descriptor-------*/
printf("openning file descriptor.............\n");
wfd=open("fifo2",O_NONBLOCK,O_WRONLY);
printf("write_fd is ok...........\n");
while((rfd=open("fifo1",O_NONBLOCK,O_RDONLY))==-1)
{
sleep(1);
printf("no response,can\'t get read_fd....\n");
}
printf("read_fd is ok...........\n");
if(rfd<=0||wfd<=0)
{
perror("open fifo failed!\n");
exit(1);
}
/*----------intercourse part------------*/
printf("this is p2\n");
printf("---------------------\n");
while(1)
{
printf("p2:");
fgets(str,256,stdin);
str[strlen(str)-1]='\0';
if(strncmp(str,"88",2)==0)
{
close(wfd);
unlink("fifo2");
close(rfd);
exit(0);
}
printf("sending messages to p1.....\n");
sleep(1);
write(wfd,str,strlen(str));
len=read(rfd,str,sizeof(str));
if(len>0)
{
str[len]='\0';
printf("p1:%s\n",str);
}
else
{
sleep(1);
printf("nothing got from p1!\n");
}
}
}