使用消息队列实现的2个终端之间的互相聊天
并使用信号控制消息队列的读取方式:
当键盘按ctrl+c的时候,切换消息读取方式,一般情况为读取指定编号的消息,
按ctrl+c之后,指定的编号不读取,读取其他所有编号的消息
1.c
typedef struct msgbuf{
long type;
char text[256];
}msg_t;
// 写进程
int msgid = 0;
void* task(void* arg){
msg_t buf = {0};
int len = 0;
while(1){
memset(&buf,0,sizeof(msg_t));
len = msgrcv(msgid,&buf,256,2,0);
if(len == 0){break;}
printf("\033[11D读取到的数据为:%s\n",buf.text);
printf("请输入:");
fflush(stdout);
}
}
int main(int argc, const char *argv[])
{
pthread_t id;
pthread_create(&id,NULL,task,NULL);
pthread_detach(id);
key_t key = ftok("./ipc",1);
if(key == -1){
perror("ftok");
return 1;
}
msgid = msgget(key,IPC_CREAT | 0666);
if(msgid == -1){
perror("msgget");
return 1;
}
msg_t buf = {0};
int len = 0;
while(1){
memset(&buf,0,sizeof(msg_t));
buf.type = 1;
printf("请输入内容:");
scanf("%256s",buf.text);
while(getchar()!=10);
len = strlen(buf.text);
msgsnd(msgid,&buf,len,0);
}
return 0;
}
2.c
typedef struct msgbuf{
long type;
char text[256];
}msg_t;
// 写进程
int msgid = 0;
void* task(void* arg){
msg_t buf = {0};
int len = 0;
while(1){
memset(&buf,0,sizeof(msg_t));
len = msgrcv(msgid,&buf,256,1,0);
if(len == 0){break;}
printf("\033[11D读取到的数据为:%s\n",buf.text);
printf("请输入:");
fflush(stdout);
}
}
int main(int argc, const char *argv[])
{
pthread_t id;
pthread_create(&id,NULL,task,NULL);
pthread_detach(id);
key_t key = ftok("./ipc",1);
if(key == -1){
perror("ftok");
return 1;
}
msgid = msgget(key,IPC_CREAT | 0666);
if(msgid == -1){
perror("msgget");
return 1;
}
msg_t buf = {0};
int len = 0;
while(1){
memset(&buf,0,sizeof(msg_t));
buf.type = 2;
printf("请输入内容:");
scanf("%256s",buf.text);
while(getchar()!=10);
len = strlen(buf.text);
msgsnd(msgid,&buf,len,0);
}
return 0;
}