消息队列案例: 单机聊天程序

This commit is contained in:
flykhan 2023-08-18 15:03:56 +08:00
parent 0903b37b35
commit c23d7e1ccc
3 changed files with 88 additions and 0 deletions

BIN
day5/chat_tool/bob Executable file

Binary file not shown.

View File

@ -0,0 +1,88 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
typedef struct msg_
{
long mType; // 消息类型
char content[100]; // 正文数据
char name[32]; // 姓名
} MSG;
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("invalid, format is : ./xx name\n");
return 1;
}
key_t key = ftok("/", 160);
int msgqid = msgget(key, IPC_CREAT | 0666);
if (msgqid == -1)
{
perror("msgget");
return 1;
}
int pid = fork();
if (pid == 0)
{
// 子进程
while (1)
{
write(STDOUT_FILENO, "我说:", 7);
MSG msg;
scanf("%s", msg.content);
strcpy(msg.name, argv[1]);
#ifdef BOB
msg.mType = 1;
#else
msg.mType = 2;
#endif
if (msgsnd(msgqid, &msg, sizeof(MSG) - sizeof(long), 0) != -1)
{
printf("send msg OK\n");
if (strncmp(msg.content, "bye", 3) == 0)
{
break;
}
}
}
// kill(getppid(), SIGSTOP);
_exit(0);
}
else if (pid > 0)
{
// 父进程
while (1)
{
MSG msg;
#ifdef BOB
msg.mType = 2;
#else
msg.mType = 1;
#endif
if (msgrcv(msgqid, &msg, sizeof(MSG) - sizeof(long), msg.mType, 0) != -1)
{
printf("\n%s >>> \"%s\"\n", msg.name, msg.content);
if (strncmp(msg.content, "bye", 3) == 0)
{
break;
}
write(STDOUT_FILENO, "我说:", 7);
}
}
// kill(pid, SIGSTOP);
wait(NULL);
}
return 0;
}

BIN
day5/chat_tool/lucy Executable file

Binary file not shown.