#includetypedef struct message_packet
{
char *name_from;
char *name_sendto;
char *msg;
}mp;
int main()
{
char name_fifo[]="fifo";
int fd_r,fd_w,i,j=0;
int rt_mf;
char buf[300]={'\0','\0','\0'};
int rp[3];
int rt_write,fd_write,rt_wait;
mp pk_slf;
pid_t pid;
rt_mf=mkfifo(name_fifo,S_IRUSR|S_IWUSR);
printf("please input your name:");
gets(buf);
pk_slf.name_from=(char *)malloc(strlen(buf)+1);
strcpy(pk_slf.name_from,buf);
pid=fork();
if(pid==0)
{
fd_write=open(name_fifo,O_WRONLY);
close(fd_write);
exit(0);
}
sleep(0.5);
rt_wait=waitpid(pid,NULL,WNOHANG);
kill(pid,SIGKILL);
if(rt_wait==0)
{
for(;;)
{
fd_r=open(name_fifo,O_RDONLY);
read(fd_r,&buf[0],300);
rp[1]=strlen(buf)+1;
rp[2]=rp[1]+strlen(&buf[rp[1]])+1;
close(fd_r);//注意
if(strcmp(buf,pk_slf.name_from)!=0)
{
fd_w=open(name_fifo,O_WRONLY);
write(fd_w,&buf[0],300);
close(fd_w);
sleep(0.2);
}
else
{
if(strlen(&buf[rp[1]])!=0)
{
printf("message frome %s:%s\n\n",&buf[rp[1]],&buf[rp[2]]);
break;
}
}
}
}
for(;;)
{
fd_w=open(name_fifo,O_WRONLY);
printf("who do you want to talk:");
gets(buf);
pk_slf.name_sendto=(char *)malloc(strlen(buf)+1);
strcpy(pk_slf.name_sendto,buf);
printf("%s:",pk_slf.name_from);
gets(buf);
pk_slf.msg=(char *)malloc(strlen(buf)+1);
strcpy(pk_slf.msg,buf);
strcpy(buf,pk_slf.name_sendto);
strcpy(&buf[strlen(buf)+1],pk_slf.name_from);
strcpy(&buf[(strlen(buf)+1)+(strlen(&buf[strlen(buf)+1])+1)],pk_slf.msg);
rt_write=write(fd_w,&buf[0],300);
close(fd_w);//注意
for(;;)
{
fd_r=open(name_fifo,O_RDONLY);
read(fd_r,&buf[0],300);
rp[1]=strlen(buf)+1;
rp[2]=rp[1]+strlen(&buf[rp[1]])+1;
close(fd_r);//注意
if(strcmp(buf,pk_slf.name_from)!=0)
{
fd_w=open(name_fifo,O_WRONLY);
write(fd_w,&buf[0],300);
close(fd_w);
sleep(0.2);
}
else
{
printf("message frome %s:%s\n\n",&buf[rp[1]],&buf[rp[2]]);
break;
}
}
}
exit(0);
}