Ubuntu互相收发消息
时间: 2024-01-01 16:57:18 浏览: 30
您可以使用 `select` 函数在 Ubuntu 上实现进程间的消息收发。`select` 函数可以监视多个文件描述符,当一个或多个文件描述符准备好进行读写时,`select` 函数会返回。
下面是一个简单的示例代码,展示了如何在两个进程之间使用管道进行消息收发:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int main() {
int pipefd[2];
pid_t pid;
char buf[1024];
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// 子进程
close(pipefd[0]); // 关闭读端
// 发送消息到父进程
const char* msg = "Hello from child process!";
write(pipefd[1], msg, strlen(msg));
close(pipefd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else {
// 父进程
close(pipefd[1]); // 关闭写端
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(pipefd[0], &read_fds);
struct timeval tv;
tv.tv_sec = 5;