使用talk
-
用户在同一台机器上talk指令格式如下:
talk 用户名@ip地址 [用户终端号]
如果用户只登录了一个终端,那么可以不写用户终端号,如:
talk user@localhost
可以使用who
指令来查看当前有哪些用户登录,他的终端号是什么
等待对方接收
-
另一个用户执行
talk root@localhost
这样就建立了一个连接,如图:
c语言写一个linux进程之间通信(聊天)的简单程序
1.实现原理
采用双FIFO架构实现全双工通信:
- 需要创建两个FIFO文件:
chat_fifo1
(客户端→服务端)和chat_fifo2
(服务端→客户端) - 服务端和客户端各自保持读写通道开放,实现实时双向通信
- 采用多线程处理读写操作,避免阻塞
2.完整代码实现
服务端代码(server.c)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>#define FIFO1 "chat_fifo1"
#define FIFO2 "chat_fifo2"void *read_thread(void *arg) {int fd = open(FIFO1, O_RDONLY);char buf[256];while(1) {if(read(fd, buf, sizeof(buf)) > 0) {printf("\r客户端: %s", buf);fflush(stdout);}}close(fd);return NULL;
}int main() {mkfifo(FIFO1, 0666);mkfifo(FIFO2, 0666);pthread_t tid;pthread_create(&tid, NULL, read_thread, NULL);int fd = open(FIFO2, O_WRONLY);char buf[256];printf("服务端就绪,输入消息(输入quit退出):\n");while(1) {printf("服务端: ");fgets(buf, sizeof(buf), stdin);if(strcmp(buf, "quit\n") == 0) break;write(fd, buf, strlen(buf)+1);}close(fd);unlink(FIFO1);unlink(FIFO2);return 0;
}
客户端代码(client.c)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>#define FIFO1 "chat_fifo1"
#define FIFO2 "chat_fifo2"void *read_thread(void *arg) {int fd = open(FIFO2, O_RDONLY);char buf[256];while(1) {if(read(fd, buf, sizeof(buf)) > 0) {printf("\r服务端: %s", buf);fflush(stdout);}}close(fd);return NULL;
}int main() {pthread_t tid;pthread_create(&tid, NULL, read_thread, NULL);int fd = open(FIFO1, O_WRONLY);char buf[256];printf("客户端就绪,输入消息(输入quit退出):\n");while(1) {printf("客户端: ");fgets(buf, sizeof(buf), stdin);if(strcmp(buf, "quit\n") == 0) break;write(fd, buf, strlen(buf)+1);}close(fd);return 0;
}
3.编译与运行
# 编译
gcc server.c -o server -lpthread
gcc client.c -o client -lpthread# 运行(需两个终端)
./server
./client
参考链接:
Linux:详解talk服务的启用和talk命令使用