Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47648
  • 博文数量: 25
  • 博客积分: 960
  • 博客等级: 准尉
  • 技术积分: 280
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-14 12:39
文章分类
文章存档

2011年(1)

2009年(20)

2008年(4)

我的朋友

分类: C/C++

2008-09-23 09:29:33

最简单的聊天程序
这个命名为: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:

呵呵~~~简单吧!!

阅读(511) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~