第一天:请使用消息队列实现2个终端之间互相聊天
singal1.c
#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <pthread.h>#include <semaphore.h>#include <wait.h>#include <signal.h>#include <sys/socket.h>#include <arpa/inet.h>#include <sys/socket.h>#include <sys/ipc.h>#include <sys/sem.h>#include <semaphore.h>#include <sys/msg.h>#include <sys/shm.h>#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;key_t key;
int id;
typedef struct msgbuf
{long channel;char buf[128];
}msg_t;void msg_w()
{msg_t msg;msg.channel = 1;while(1){memset(msg.buf,0,128);//printf("张三:");scanf("%s",msg.buf);while(getchar()!=10);msgsnd(id,&msg,strlen(msg.buf),0);}
}void msg_r()
{msg_t msg = {0};while(1){memset(msg.buf,0,128);msgrcv(id,&msg,128,2,0);printf("好友李四:%s\n",msg.buf);}}void* pthread_main(void* arg)
{msg_w();
}void handler(int signum)
{if(SIGINT == signum){msgctl(id,IPC_RMID,NULL);exit(0);}
}int main(int argc, const char *argv[])
{key = ftok("./ipc",2);id = msgget(key,IPC_CREAT | 0666);pthread_t pthread_id;signal(SIGINT,handler);pthread_create(&pthread_id,0,pthread_main,NULL);pthread_detach(pthread_id);msg_r();return 0;
}
singal2.c
#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <pthread.h>#include <semaphore.h>#include <wait.h>#include <signal.h>#include <sys/socket.h>#include <arpa/inet.h>#include <sys/socket.h>#include <sys/ipc.h>#include <sys/sem.h>#include <semaphore.h>#include <sys/msg.h>#include <sys/shm.h>#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;key_t key;
int id;
typedef struct msgbuf
{long channel;char buf[128];
}msg_t;void msg_w()
{msg_t msg;msg.channel = 2;while(1){memset(msg.buf,0,128);//printf("李四:");scanf("%s",msg.buf);while(getchar()!=10);msgsnd(id,&msg,strlen(msg.buf),0);}
}void msg_r()
{msg_t msg = {0};while(1){memset(msg.buf,0,128);msgrcv(id,&msg,128,1,0);printf("好友张三:%s\n",msg.buf);}}void* pthread_main(void* arg)
{msg_r();
}void handler(int signum)
{if(SIGINT == signum){msgctl(id,IPC_RMID,NULL);exit(0);}
}int main(int argc, const char *argv[])
{key = ftok("./ipc",2);id = msgget(key,IPC_CREAT | 0666);pthread_t pthread_id;signal(SIGINT,handler);pthread_create(&pthread_id,0,pthread_main,NULL);pthread_detach(pthread_id);msg_w();return 0;
}