📜  pipe()系统调用(1)

📅  最后修改于: 2023-12-03 15:03:46.921000             🧑  作者: Mango

简介

在Unix和Linux系统中,pipe()是一种常用的系统调用,它可以创建一个连接两个进程的管道,使得一个进程的输出可以直接用作另一个进程的输入。这种通信方式通常被称为"管道通信"。

在C语言中,我们可以通过pipe()来创建管道,然后使用fork()创建子进程,使得父进程和子进程之间可以通过管道来进行通信。

创建管道

下面是一个简单的示例程序,它演示如何使用pipe()来创建管道:

#include <stdio.h>
#include <unistd.h>

int main() {
    int fd[2];
    char buf[20];
    if (pipe(fd) == -1) {
        perror("pipe error");
        return 1;
    }
    if (fork() == 0) {
        // 子进程
        close(fd[1]);  // 关闭写端
        read(fd[0], buf, sizeof(buf));
        printf("child received data: %s\n", buf);
        close(fd[0]);
    } else {
        // 父进程
        close(fd[0]);  // 关闭读端
        write(fd[1], "hello world", 12);
        close(fd[1]);
    }
    return 0;
}

在这个程序中,我们首先使用pipe()创建了一个包含两个文件描述符的整型数组fd,这两个文件描述符分别代表了管道的输入端和输出端。然后我们调用fork()创建了一个子进程。在子进程中,我们关闭了管道的输出端,然后使用read()从管道的输入端读取数据,并打印出来。在父进程中,我们关闭了管道的输入端,然后使用write()往管道的输出端写入数据。

管道通信

通过管道通信,我们可以实现父进程和子进程之间的通信。下面是一个使用管道通信的示例程序:

#include <stdio.h>
#include <unistd.h>

int main() {
    int fd[2];
    char buf[20];
    if (pipe(fd) == -1) {
        perror("pipe error");
        return 1;
    }
    if (fork() == 0) {
        // 子进程
        close(fd[1]);  // 关闭写端
        while (read(fd[0], buf, sizeof(buf)) > 0) {
            printf("child received data: %s\n", buf);
        }
        close(fd[0]);
    } else {
        // 父进程
        close(fd[0]);  // 关闭读端
        write(fd[1], "hello", 5);
        write(fd[1], "world", 5);
        close(fd[1]);
    }
    return 0;
}

在这个程序中,我们先创建了一个管道。然后我们创建了一个子进程,在子进程中使用read()从管道的输入端读取数据,并打印出来。在父进程中,我们使用write()往管道的输出端写入数据。这样,当父进程写入数据时,子进程就能够接收到相应的数据。在这个程序中,我们写入了两个字符串"hello"和"world",并分别打印出来。

总结

pipe()系统调用是Unix和Linux系统中的一种常用系统调用,它可以创建一个连接两个进程的管道,实现进程之间的通信。在程序设计中,我们可以通过创建管道和使用管道通信来实现进程之间的数据传输。