FD_SET 和 select 来同时监视多个文件描述符

下面是一个简单的多进程示例,它展示了如何使用 fork 创建子进程,并用 FD_SET 和 select 来同时监视多个文件描述符。这个示例演示了父进程和子进程如何处理输入和输出:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/select.h>
#include <fcntl.h>

#define MAX_FDS 2

int main() {
    int pipe_fd[2];
    pid_t pid;
    fd_set read_fds;
    int max_fd;

    // 创建管道
    if (pipe(pipe_fd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    if ((pid = fork()) == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) { // 子进程
        close(pipe_fd[0]); // 关闭读端
        char msg[] = "Hello from child\n";
        write(pipe_fd[1], msg, sizeof(msg)); // 向管道写入数据
        close(pipe_fd[1]); // 关闭写端
        exit(EXIT_SUCCESS);
    } else { // 父进程
        close(pipe_fd[1]); // 关闭写端
        while (1) {
            FD_ZERO(&read_fds);
            FD_SET(pipe_fd[0], &read_fds);
            max_fd = pipe_fd[0];

            // 使用 select 监视管道的读端
            if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1) {
                perror("select");
                exit(EXIT_FAILURE);
            }

            // 检查是否有数据可读
            if (FD_ISSET(pipe_fd[0], &read_fds)) {
                char buf[256];
                ssize_t bytes_read = read(pipe_fd[0], buf, sizeof(buf) - 1);
                if (bytes_read > 0) {
                    buf[bytes_read] = '\0'; // 添加字符串结束符
                    printf("Received: %s", buf);
                }
                close(pipe_fd[0]); // 关闭管道读端
                break; // 退出循环
            }
        }
        wait(NULL); // 等待子进程结束
    }

    return 0;
}

在这个示例中:

  1. 父进程和子进程通过管道进行通信。
  2. 父进程使用 select 来监视管道的读端是否有数据可读。
  3. 子进程向管道写入数据,然后退出。
  4. 父进程在 select 检测到管道有数据可读时,读取并打印数据,然后退出。
    这样,父进程和子进程通过 pipe 和 select 实现了基本的进程间通信。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值