C语言 linux 实现在线聊天

这篇博客详细介绍了如何通过创建进程、利用文件打开和读取以及Linux管道文件,在用户1和用户2之间建立一个简单的消息传递系统。用户可以在各自的终端上交互发送消息,直到输入'!q'退出。程序涉及的知识点包括进程控制、文件操作以及管道通信,为理解多进程间通信提供了一个实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果

在这里插入图片描述
功能:user1和user2互发消息。

运用的知识

  • 创建进程
  • 文件打开和读取
  • linux管道文件

具体实现代码

1.首先在同一个文件夹下创建两个管道文件

mkfifo f1
mkfifo f2

2.写上代码
user1.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//文件处理相关库
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 
    pid_t pid = fork();
    if(pid < 0){
        perror("fork");
        return -1;
    }
    else if(pid == 0){
        //发消息给user2
        int fd = open("./f2",O_WRONLY);
        char buf[20]={0};
        while(1){
            gets(buf);
            if(strcmp(buf,"!q")==0){
                exit(0);
            }
            write(fd, buf, strlen(buf));
        }
    }
    else{
        printf("user1---------------------\n");
        //接受user2发过来的消息
        int fd = open("./f1",O_RDONLY);
        char buf[100] = {0};
        int n;
        while(1){
            n = read(fd, buf, sizeof(buf));
            if(n==0) break;
            printf("user2: %s\n", buf);
            memset(buf, 0, sizeof(buf));
        }
    }
    return 0;
} 

user2的代码和user1的差不多,就是提示文本不同而已
user2.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 
    pid_t pid = fork();
    if(pid < 0){
        perror("fork");
        return -1;
    }
    else if(pid == 0){
        //发消息给user1
        int fd = open("./f1",O_WRONLY);
        char buf[20]={0};
        while(1){
            gets(buf);
            if(strcmp(buf,"!q")==0){
                
                exit(0);
            }
            write(fd, buf, strlen(buf));
        }
    }
    else{
        //接受user1发过来的消息
        printf("user2-------------\n");
        int fd = open("./f2",O_RDONLY);
        char buf[100] = {0};
        int m;
        while(1){
            m = read(fd, buf, sizeof(buf));
            if(m==0) break;
            printf("user1:%s\n", buf);
            memset(buf, 0, sizeof(buf));
        }
    }
    return 0;
} 

3.编译运行

gcc user1.c -o user1
gcc user2.c -o user2

打开两个终端,第一个终端输入 ./user1 第二个输入 ./user2
完成。
ctrl+c 停止聊天

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值