首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在mono/Linux下从命名管道读/写

在 Linux 下,命名管道(named pipe)是一种特殊类型的文件,用于在不同进程之间进行数据传输。命名管道有两种类型:FIFO 和 socketpair。

从命名管道读取数据的方法是使用 open() 系统调用打开管道,然后使用 read() 系统调用从管道中读取数据。例如:

代码语言:c
复制
#include<stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd;
    char buf[1024];

    // 打开命名管道
    fd = open("my_pipe", O_RDONLY);
    if (fd < 0) {
        perror("open");
        exit(1);
    }

    // 从管道中读取数据
    int n = read(fd, buf, sizeof(buf));
    if (n < 0) {
        perror("read");
        exit(1);
    }

    // 输出读取到的数据
    printf("Read %d bytes from the pipe: %s\n", n, buf);

    // 关闭管道
    close(fd);

    return 0;
}

从命名管道写入数据的方法是使用 open() 系统调用打开管道,然后使用 write() 系统调用向管道中写入数据。例如:

代码语言:c
复制
#include<stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd;
    char buf[] = "Hello, world!";

    // 打开命名管道
    fd = open("my_pipe", O_WRONLY);
    if (fd < 0) {
        perror("open");
        exit(1);
    }

    // 向管道中写入数据
    int n = write(fd, buf, sizeof(buf));
    if (n < 0) {
        perror("write");
        exit(1);
    }

    // 关闭管道
    close(fd);

    return 0;
}

需要注意的是,命名管道是一种同步 I/O 方式,如果读取或写入的进程没有准备好,则会阻塞。如果需要异步 I/O,则需要使用其他方式,例如使用套接字(socket)进行通信。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券