qfedu-linux-advanced-level/day5/chat_tool/chat_tool.c

89 lines
1.9 KiB
C
Raw Normal View History

2023-08-18 15:03:56 +08:00
#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;
}