使用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命令使用