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

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

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

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

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

下面我将展示几种不同的IPC方式实现的简单聊天程序。

1. 使用命名管道(FIFO)

server.c (服务器端)

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 (客户端)

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;
}

三、编译和运行

命名管道版本

  1. 编译:

    bash 复制代码
    gcc server.c -o server
    gcc client.c -o client
  2. 在两个不同的终端中分别运行:

    bash 复制代码
    ./server
    ./client


相关推荐
NULL指向我23 分钟前
香橙派3B学习笔记2:Vscode远程SSH登录香橙派_权限问题连接失败解决
笔记·vscode·学习
炎码工坊29 分钟前
云原生安全之PaaS:从基础到实践的技术指南
运维·安全·网络安全·云原生·运维开发
hello1114-31 分钟前
Redis学习打卡-Day5-Redis 持久化
数据库·redis·学习
张国荣家的弟弟1 小时前
为何在VMware中清理CentOS虚拟机后,本地磁盘空间未减少的问题解决
linux·运维·centos
小程同学>o<1 小时前
嵌入式开发之STM32学习笔记day10
经验分享·笔记·stm32·单片机·嵌入式硬件·学习
叒卮1 小时前
小白学习顺序表 之 通讯录实现
c语言·数据结构·学习
甘北1 小时前
docker commit除了提交容器成镜像,还能搞什么之修改cmd命令
linux·运维·docker
江畔柳前堤1 小时前
PyQt学习系列05-图形渲染与OpenGL集成
开发语言·javascript·人工智能·python·学习·ecmascript·pyqt
吐泡泡_2 小时前
动静态库--
linux
努力学习的小廉2 小时前
深入了解linux系统—— 操作系统的路径缓冲与链接机制
android·linux·服务器