The inter-process communication Named pipes

Named pipe (FIFO) is a way of inter-process communication.

API:

int mkfifo(const char *pathname, mode_t mode);

DEMO:

// 写进程
int main(int argc, char **argv) {
    char filename[] = "/tmp/my_fifo";
    if (mkfifo(filename, 0777) < 0) {
        perror("mkfifo error");
        exit(1);
    }
    int fd = open(filename, O_WRONLY);
    char buffer[128] = "hello world";
    write(fd, buffer, strlen(buffer));
    printf("write done\n");
    return 0;
}

// 读进程
int main(int argc, char **argv) {
    char filename[] = "/tmp/my_fifo";
    int fd = open(filename, O_RDONLY);
    char buffer[128];
    int n = read(fd, buffer, 128);
    buffer[n] = '\0';
    printf("input is : %s\n", buffer);
    return 0;
}

Two things to note:

1. mkfifo my_fifo creates a file in the / tmp directory

2. Before reading process open, write process is blocked

   (it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it.)

 

And pipes compared named pipe can be used for any communication between two processes.

Reproduced in: https: //www.cnblogs.com/gattaca/p/6547580.html

Guess you like

Origin blog.csdn.net/weixin_33881050/article/details/93519920