当前位置: 首页 > news >正文

Linux学习——Linux进程间通信(IPC)聊天程序实践

Linux学习——Linux进程间通信(IPC)聊天程序实践

一、在阿里云服务器上使用talk程序

Linux系统自带的talk命令可以让两个登录用户进行实时文字聊天:

  1. 用户A执行:talk usernameB
  2. 用户B会收到通知,并需要执行: talk usernameA@hostname
  3. 然后双方就可以开始聊天了,屏幕会分成上下两部分
  4. image-20250420181514161

image-20250420181343202

二、用C语言实现简单的进程间的通信聊天程序

1.使用命令管理(FIFO)

server.c(服务器端)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stddef.h>  // 添加 size_t 的定义#define FIFO_FILE "chat_fifo"int main() {int fd;char readbuf[80];char end[10];int to_end;// 创建命名管道mkfifo(FIFO_FILE, 0666);while(1) {fd = open(FIFO_FILE, O_RDONLY);read(fd, readbuf, sizeof(readbuf));printf("Client: %s\n", readbuf);close(fd);printf("Server: ");fgets(readbuf, sizeof(readbuf), stdin);strcpy(end, "quit\n");to_end = strcmp(readbuf, end);if (to_end == 0) {fd = open(FIFO_FILE, O_WRONLY);write(fd, readbuf, strlen(readbuf));close(fd);break;}fd = open(FIFO_FILE, O_WRONLY);write(fd, readbuf, strlen(readbuf));close(fd);}unlink(FIFO_FILE);  // 删除FIFO文件return 0;
}

client.c(客户端)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stddef.h>  // 添加 size_t 的定义#define FIFO_FILE "chat_fifo"int main() {int fd;char readbuf[80];char end[10];int to_end;while(1) {printf("Client: ");fgets(readbuf, sizeof(readbuf), stdin);strcpy(end, "quit\n");to_end = strcmp(readbuf, end);fd = open(FIFO_FILE, O_WRONLY);write(fd, readbuf, strlen(readbuf));close(fd);if (to_end == 0) {break;}fd = open(FIFO_FILE, O_RDONLY);read(fd, readbuf, sizeof(readbuf));printf("Server: %s\n", readbuf);close(fd);}return 0;
}

2.编译和运行

  • 编译
gcc server.c -o server
gcc client.c -o client
  • 在两个不同的终端分别运行
./server
./client

2.编译和运行

  • 编译
gcc server.c -o server
gcc client.c -o client
  • 在两个不同的终端分别运行
./server
./client

image-20250420124240561

http://www.xdnf.cn/news/51517.html

相关文章:

  • Android开发中广播(Broadcast)技术详解
  • 线程基础题
  • FOC控制中的正弦PWM和空间矢量PWM对比与理解
  • 【计量地理学】实验五 试验变异函数计算
  • 软件设计师/系统架构师---计算机网络
  • Python爬虫实战:获取fenbi网最新备考资讯
  • 机器学习专栏(4):从数据饥荒到模型失控,破解AI训练的七大生死劫
  • SpringBoot Actuator健康检查:自定义HealthIndicator
  • Java 8 date/time type `java.time.LocalDateTime`
  • FreeRTOS中断管理
  • LangChain4j对话内存管理:ChatMemory原理与实战应用
  • 【深度学习与大模型基础】第12章-损失函数与梯度下降
  • 高等数学同步测试卷 同济7版 试卷部分 上 做题记录 上册期中同步测试卷 B卷
  • 相对路径和绝对路径解析
  • windows下配置Ninja
  • 算法笔记—动态规划
  • Multisim使用教程详尽版--(2025最新版)
  • B树的异常恢复
  • pivot_root:原理、用途及最简单 Demo
  • 项目预期管理:超越甘特图,实现客户价值交付
  • 协程?协程与线程的区别?Java是否支持协程?
  • The_Planets_Earth靶场笔记(VulnHub)
  • 第一章,HCIA复习
  • 人形机器人马拉松:北京何以孕育“领跑者”?
  • C++ 基础:注意a == b; b == a;陷阱
  • 如何高效利用呼叫中心系统和AI语音机器人
  • (12)VTK C++开发示例 --- 生成高斯随机数
  • 苍穹外卖阶段性总结 (超详细版)
  • AIGC(生成式AI)试用 30 -- AI做软件程序测试 1
  • Redis入门