最简单的聊天程序
这个命名为:Bigelephant.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PROJID 0xFF
#define SNDMSG 1
#define RCVMSG 2
int mqid;
void terminate_handler(int signo)
{
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}
int main()
{
char filenm[]="share-data";
key_t mqkey;
struct msgbuf{
long mtype;
char mtext[1024];
}msg;
int ret;
mqkey=ftok(filenm,PROJID);
if(mqkey==-1){
perror("ftok error!\n");
exit(-1);
}
mqid=msgget(mqkey,IPC_CREAT | IPC_EXCL |0666);
if(mqid==-1){
perror("msgget error!\n");
exit(-1);
}
signal(SIGINT,terminate_handler);
signal(SIGTERM,terminate_handler);
while(1){
printf("Big elephant: ");
fgets(msg.mtext,1024,stdin);
if(strncmp("quit",msg.mtext,4)==0){
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}
msg.mtext[strlen(msg.mtext)-1]='\0';
msg.mtype=SNDMSG;
msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
msgrcv(mqid,&msg,1024,RCVMSG,0);
printf("Small elephant: %s\n",msg.mtext);
}
}
这个命名为:Smallelephant.c
#include
#include
#include
#include
#include
#include
#include
#define PROJID 0xFF
#define SNDMSG 1
#define RCVMSG 2
int main(void)
{
char filenm[]="share-data";
int mqid;
key_t mqkey;
struct msgbuf{
long mtype;
char mtext[1024];
}msg;
int ret;
mqkey=ftok(filenm,PROJID);
if(mqkey==-1){
perror("ftok error!\n");
exit(-1);
}
mqid=msgget(mqkey,0);
if(mqid==-1){
perror("msgget error!\n");
exit(-1);
}
while(1){
msgrcv(mqid,&msg,1024,SNDMSG,0);
printf("Big elephant: %s\n",msg.mtext);
printf("Small elephant: ");
fgets(msg.mtext,1024,stdin);
if(strncmp("quit",msg.mtext,4)==0){
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}
msg.mtext[strlen(msg.mtext)-1]='\0';
msg.mtype=RCVMSG;
msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
}
}
再在当前目录下新建一个shara-dat文件,再分别打开两个终端,先运行Bigelephant ,后运行Smallelephant
例如:
[xiang@localhost xiang]$ ./Bigelephant
Big elephant: hello
Small elephant: hi
Big elephant: are you small elephant?
Small elephant: yes
Big elephant: OK
Small elephant: are you Big elephant?
Big elephant: yes
Small elephant: Good
Big elephant: Goodbye
Small elephant: Bye
Big elephant:
呵呵~~~简单吧!!
阅读(540) | 评论(0) | 转发(0) |