/*
进程间通信,这是用一根管道实现的一个简单的多人聊天程序,缺点是一个时间点只能有一个用户输入聊天信息,只有别人给你发送信息之后你才有权输入信息发送信息,发送信息之后输入的权力便交出去了,优点是较少出错(当然,是相对于程序(二)而言,其实鲁棒性依然比较差,有待改进);
希望的到大家的指正;
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef struct message_packet
{
char *name_from;
char *name_sendto;
char *msg;
}mp;
int main()
{
char name_fifo[]="fifo_talk";
int fd_w,fd_r,i,j=0;
int rt_mf;
char buf[300]={'\0','\0','\0','\0'};
int rp[3];
int rt_read,rt_wait,rt_write,fd_read;
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_read=open(name_fifo,O_RDONLY);
close(fd_read);
exit(0);
}
sleep(0.5);
rt_wait=waitpid(pid,NULL,WNOHANG);
kill(pid,SIGKILL);
if(rt_wait==0)
{
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);
write(fd_w,&buf[0],300);
close(fd_w);
}
for(;;)
{
for(;;)
{
fd_r=open(name_fifo,O_RDONLY);
rt_read=read(fd_r,&buf[0],300);
close(fd_r);
rp[1]=strlen(buf)+1;
rp[2]=rp[1]+strlen(&buf[rp[1]])+1;
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;
}
}
}
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);
write(fd_w,&buf[0],300);
close(fd_w);
}
exit(0);
}
阅读(1982) | 评论(1) | 转发(0) |