用c语言实现两个进程交互式聊天
时间: 2023-03-23 11:00:34 浏览: 144
要用C语言实现两个进程之间的交互式聊天,可以使用进程间通信(IPC)机制来实现。其中,最常见的方式是使用管道(Pipe)或者套接字(Socket)。
以下是使用管道实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 100
int main()
{
int pipefd[2];
pid_t pid;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
char buffer[BUFFER_SIZE];
while (1) {
int n = read(pipefd[0], buffer, BUFFER_SIZE);
if (n == -1) {
perror("read");
exit(EXIT_FAILURE);
} else if (n == 0) { // 管道已经关闭
printf("对方已经退出聊天。\n");
break;
} else {
printf("接收到消息: %s", buffer);
}
}
close(pipefd[0]); // 关闭读端
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[0]); // 关闭读端
char buffer[BUFFER_SIZE];
while (1) {
printf("请输入消息:");
fgets(buffer, BUFFER_SIZE, stdin);
if (strcmp(buffer, "exit\n") == 0) { // 输入exit退出聊天
break;
}
int n = write(pipefd[1], buffer, strlen(buffer));
if (n == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
close(pipefd[1]); // 关闭写端
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
return 0;
}
```
运行上述代码后,父进程会等待用户输入消息并发送到管道中,子进程则等待管道中有消息并接收打印。输入exit后会退出聊天,父进程会等待子进程结束后退出。
这只是一个简单的示例代码,实际聊天程序需要更多的功能和安全保障。另外,也可以使用套接字(Socket)实现更为复杂的网络聊天。