使用消息队列实现的2个终端之间的互相聊天
并使用信号控制消息队列的读取方式:
当键盘按ctrl+c的时候,切换消息读取方式,一般情况为读取指定编号的消息,按ctrl+c之后,指定的编号不读取,读取其他所有编号的消息
typedef struct msgInformation { long type; char text[128]; } msg; key_t key; int msgid; int msgflag = 0; void chflag(int signum) { msgflag = msgflag == 0 ? 020000 : 0; } void *sendmsg_thread(void *arg) { msg msg; while (1) { memset(&msg, 0, sizeof(msg)); msgrcv(msgid, &msg, sizeof(msg), 1, msgflag); printf("B:%s\n",msg.text); } } int main(int argc, char const *argv[]) { pthread_t thread; if (pthread_create(&thread, NULL, sendmsg_thread, NULL) != 0) { printf("pthread_create error\n"); return -1; } if ((key = ftok("./ipc",2)) == -1) { perror("ftok"); return -1; } if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1) { printf("msgget error\n"); return -1; } signal(SIGINT, chflag); msg msg; while (1) { msg.type = 2; printf("Ainput:"); scanf("%s", msg.text); while(getchar() != '\n'); msgsnd(msgid, &msg, strlen(msg.text), 0); } return 0; }
typedef struct msgInformation { long type; char text[128]; } msg; key_t key; int msgid; int msgflag = 0; void chflag(int signum) { msgflag = msgflag == 0 ? 020000 : 0; } void *sendmsg_thread(void *arg) { msg msg; while (1) { msg.type = 1; printf("B输入:"); scanf("%s", msg.text); while(getchar() != '\n'); msgsnd(msgid, &msg, strlen(msg.text), 0); } } int main(int argc, char const *argv[]) { pthread_t thread; if (pthread_create(&thread, NULL, sendmsg_thread, NULL) != 0) { printf("pthread_create error\n"); return -1; } if ((key = ftok("./ipc",2)) == -1) { perror("ftok"); return -1; } if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1) { printf("msgget error\n"); return -1; } signal(SIGINT, chflag); msg msg; while (1) { memset(&msg, 0, sizeof(msg)); msgrcv(msgid, &msg, sizeof(msg), 2, msgflag); printf(" A > %s\n",msg.text); } return 0; }
IO进程线程学习day7
于 2024-05-14 08:55:24 首次发布