Home php教程 PHP开发 pipe() function in linux programming

pipe() function in linux programming

Dec 13, 2016 am 11:31 AM
linux pipe

管道是一种把两个进程之间的标准输入和标准输出连接起来的机制,从而提供一种让多个进程间通信的方法,当进程创建管道时,每次

都需要提供两个文件描述符来操作管道。其中一个对管道进行写操作,另一个对管道进行读操作。对管道的读写与一般的IO系统函数一

致,使用write()函数写入数据,使用read()读出数据。

pipe() function in linux programming

#include

int pipe(int filedes[2]);

返回值:成功,返回0,否则返回-1。参数数组包含pipe使用的两个文件的描述符。fd[0]:读管道,fd[1]:写管道。

必须在fork()中调用pipe(),否则子进程不会继承文件描述符。两个进程不共享祖先进程,就不能使用pipe。但是可以使用命名管道。

pipe() function in linux programming

pipe() function in linux programming

pipe() function in linux programming

当管道进行写入操作的时候,如果写入的数据小于128K则是非原子的,如果大于128K字节,缓冲区的数据将被连续地写入

管道,直到全部数据写完为止,如果没有进程读取数据,则将一直阻塞,如下:

pipe() function in linux programming

pipe() function in linux programming

pipe() function in linux programming

pipe() function in linux programming

在上例程序中,子进程一次性写入128K数据,当父进程将全部数据读取完毕的时候,子进程的write()函数才结束阻塞并且

返回写入信息。

命名管道FIFO

管道最大的劣势就是没有名字,只能用于有一个共同祖先进程的各个进程之间。FIFO代表先进先出,单它是一个单向数据流,也就是半双工,和

管道不同的是:每个FIFO都有一个路径与之关联,从而允许无亲缘关系的进程访问。  

        #include

        #include

      int mkfifo(const char *pathname, mode_t mode);
     这里pathname是路径名,mode是sys/stat.h里面定义的创建文件的权限.

以下示例程序来自:http://blog.chinaunix.net/uid-20498361-id-1940238.html

  有亲缘关系进程间的fifo的例子

/*
 * 有亲缘关系的进程间的fifo的使用
 * fifo 使用的简单例子
 */

#include "../all.h"

#define FIFO_PATH "/tmp/hover_fifo"


void 
do_sig(int signo)
{
    if (signo == SIGCHLD)
        while (waitpid(-1, NULL, WNOHANG) > 0)
            ;
}

int
main(void)
{
    int ret;
    int fdr, fdw;
    pid_t pid;

    char words[10] = "123456789";
    char buf[10] = {'\0'};    
    
    // 创建它,若存在则不算是错误,
    // 若想修改其属性需要先打开得到fd,然后用fcntl来获取属性,然后设置属性.

    if (((ret = mkfifo(FIFO_PATH, FILE_MODE)) == -1) 
                     && (errno != EEXIST))
        perr_exit("mkfifo()");
    fprintf(stderr, "fifo : %s created successfully!\n", FIFO_PATH);

    signal(SIGCHLD, do_sig);

    pid = fork();
    if (pid == 0) { // child

        if ((fdr = open(FIFO_PATH, O_WRONLY)) < 0) // 打开fifo用来写
            perr_exit("open()");
        sleep(2);
        // 写入数据
        if (write(fdr, words, sizeof(words)) != sizeof(words)) 
            perr_exit("write");
        fprintf(stderr, "child write : %s\n", words);
        close(fdw);
    } else if (pid > 0) { // parent

        if ((fdr = open(FIFO_PATH, O_RDONLY)) < 0) // 打开fifo用来读

            perr_exit("open()");

        fprintf(stderr, "I father read, waiting for child ...\n");
        if (read(fdr, buf, 9) != 9) //读数据
            perr_exit("read");

        fprintf(stderr, "father get buf : %s\n", buf);
        close(fdr);
    }
    // 到这里fifo管道并没有被删除,必须手动调用函数unlink或remove删除.

    return 0;    
}
Copy after login

从例子上可以看出使用fifo时需要注意:
*fifo管道是先调用mkfifo创建,然后再用open打开得到fd来使用.
*在打开fifo时要注意,它是半双工的的,一般不能使用O_RDWR打开,而只能用只读或只写打开.

fifo可以用在非亲缘关系的进程间,而它的真正用途是在服务器和客户端之间. 由于它是半双工的所以,如果要进行客户端和服务器双方的通信的话,

每个方向都必须建立两个管道,一个用于读,一个用于写.

下面是一个服务器,对多个客户端的fifo的例子:

server 端的例子:

/*
 * FIFO server
 */

#include "all.h"

int
main(void)
{
    int fdw, fdw2;
    int fdr;
    char clt_path[PATH_LEN] = {&#39;\0&#39;};
    char buf[MAX_LINE] = {&#39;\0&#39;};
    char *p;
    int n;
    
    if (mkfifo(FIFO_SVR, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");    
    if ((fdr = open(FIFO_SVR, O_RDONLY)) < 0)    
        perr_exit("open()");
    /* 
     * 根据fifo的创建规则, 若从一个空管道或fifo读, 
     * 而在读之前管道或fifo有打开来写的操作, 那么读操作将会阻塞 
     * 直到管道或fifo不打开来读, 或管道或fifo中有数据为止. 
     *
     * 这里,我们的fifo本来是打开用来读的,但是为了,read不返回0,
     * 让每次client端读完都阻塞在fifo上,我们又打开一次来读.
     * 见unpv2 charper 4.7
     */
    if ((fdw2 = open(FIFO_SVR, O_WRONLY)) < 0)    
        fprintf(stderr, "open()");
    
    while (1) {
        /* read client fifo path from FIFO_SVR */
     /* 这里由于FIFO_SVR有打开来写的操作,所以当管道没有数据时, 
      * read会阻塞,而不是返回0. 
      */
        if (read(fdr, clt_path, PATH_LEN) < 0) {
            fprintf(stderr, "read fifo client path error : %s\n", strerror(errno));    
            break;
        }
        if ((p = strstr(clt_path, "\r\n")) == NULL) {
            fprintf(stderr, "clt_path error: %s\n", clt_path);
            break;
        }
        *p = &#39;\0&#39;;
        DBG("clt_path", clt_path);
        if (access(clt_path, W_OK) == -1) { // client fifo ok, but no permission

            perror("access()");    
            continue;
        }
        /* open client fifo for write */
        if ((fdw = open(clt_path, O_WRONLY)) < 0) {
            perror("open()");    
            continue;
        }
        if ((n = read(fdr, buf, WORDS_LEN)) > 0) { /* read server words is ok */
            printf("server read words : %s\n", buf);
            buf[n] = &#39;\0&#39;;
            write(fdw, buf, strlen(buf));    
        }
    }
    
    close(fdw);    
    unlink(FIFO_SVR);
    exit(0);
}
Copy after login

客户端的例子:

/*
 * Fifo client
 *
 */
#include "all.h"



int
main(void)
{
    int fdr, fdw;
    pid_t pid;    
    char clt_path[PATH_LEN] = {&#39;\0&#39;};
    char buf[MAX_LINE] = {&#39;\0&#39;};
    char buf_path[MAX_LINE] = {&#39;\0&#39;};
    
    snprintf(clt_path, PATH_LEN, FIFO_CLT_FMT, (long)getpid());        
    DBG("clt_path1 = ", clt_path);
    snprintf(buf_path, PATH_LEN, "%s\r\n", clt_path);

    if (mkfifo(clt_path, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");

    /* client open clt_path for read
     * open server for write 
       */
    if ((fdw = open(FIFO_SVR, O_WRONLY)) < 0) 
        perr_exit("open()");
    
    /* write my fifo path to server */    
    if (write(fdw, buf_path, PATH_LEN) != PATH_LEN)        
        perr_exit("write()");
    if (write(fdw, WORDS, WORDS_LEN) < 0)    /* write words to fifo server */
        perr_exit("error");

    if ((fdr = open(clt_path, O_RDONLY)) < 0)    
        perr_exit("open()");
    if (read(fdr, buf, WORDS_LEN) > 0) {     /* read reply from fifo server */
        buf[WORDS_LEN] = &#39;\0&#39;;
        printf("server said : %s\n", buf);
    }
    
    close(fdr);
    unlink(clt_path);
    
    exit(0);
}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to switch Chinese mode with vscode How to switch Chinese mode with vscode Apr 15, 2025 pm 11:39 PM

VS Code To switch Chinese mode: Open the settings interface (Windows/Linux: Ctrl, macOS: Cmd,) Search for "Editor: Language" settings Select "Chinese" in the drop-down menu Save settings and restart VS Code

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

See all articles