Inter-process communication--unnamed pipes and named pipes

Table of contents

Communication between threads

process characteristics

Why do we need inter-process communication and what can inter-process communication do?

1. Inter-process communication method

2. Nameless pipes

features

functional interface

Precautions

practise

operation result

3. Famous pipeline

features

functional interface

Precautions

4. Summary

The difference between named pipes and unnamed pipes


Communication between threads

global variable

process characteristics

The system will allocate 0-4g virtual space for each process, 0-3g (user space) is unique to each process, and 3g-4g (kernel space) is shared by all processes.

When the CPU schedules a process, it will allocate a time slice (a few milliseconds to more than ten milliseconds) to the process. When the time slice is used up, the CPU will schedule other processes to realize the rotation of the process, thereby realizing multi-tasking operations.

Why do we need inter-process communication and what can inter-process communication do?

1).Data transmission

A process needs to send its data to another process;

2). Resource sharing

Share the same resource among multiple processes;

3).Notification event

A process needs to send a message to another process or group of processes informing them that some event has occurred;

4). Process control

Some processes want to completely control the execution of another process (such as the Debug process), and the control process hopes to be able to intercept all operations of another process and know its state changes in time.

1. Inter-process communication method

Early interprocess communication: unnamed pipes, named pipes, signals

system V IPC objects: shared memory, semaphore sets, message queues

BSD:socket

2. Nameless pipes

features

a. Anonymous can only be used for correspondence with kinship.

b. Half-duplex communication, with a fixed read end and write end.

(Simplex: one direction, TV, radio.

Half-duplex: It can be bidirectional, but can only be in one direction at the same time.

Full-duplex: can be two-way at the same time. )

c. The unnamed pipe can be regarded as a special file. For its reading and writing, file IO such as read and write can be used.

d. The unnamed pipe communicates with the file descriptor. When the pipe is established, two file descriptors are automatically created, fd[0] reads the pipe, and fd[1] writes the pipe.

functional interface

int pipe(int fd[2])

Function: create an unnamed pipe

Parameters: file descriptor fd[0]: read end fd[1] : write end

Return value: success 0

fail -1

Precautions

  1. When there is no data in the pipeline, the read operation is blocked; if there is no data in the pipeline, the write end is closed, and the read operation returns immediately;
  2. When the pipeline is full of 64k, the write is blocked, the 4k space is read, and the write continues;
  3. Only when the read end of the pipeline exists, it is meaningful to write data to the pipeline, which will cause the pipeline to break and the kernel to send the SIGPIPE signal.

practise

The parent-child process realizes the communication, the parent process cyclically inputs data from the terminal, and the child process cyclically prints, and ends when quit is input.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char const *argv[])
{
    int fd[2] = {0};//定义两个文件描述符
    char buf[32] ="";
    int pfd=pipe(fd);
    if (pfd < 0)//1.先创建无名管道
    {
        perror("pipe err");
        return -1;
    }
    printf("fd[0]:%d fd[1]:%d\n", fd[0],fd[1]);//读端、写端
    
    pid_t pid = fork();//2.后创建父子进程,拿到同一个管道
    if(pid<0)
    {
        perror("pipe err");
        return -1;
    }
    else if (pid == 0)
    {
        while (1)
        {
            read(fd[0], buf, 32);
            if (!strcmp(buf, "quit"))
                break;
            printf("buf:%s\n", buf);
        }
    }
    else{
        while (1)
        {
            scanf("%s", buf);
            write(fd[1], buf, 32);
            if (!strcmp(buf, "quit"))
                break;
        }
        wait(NULL);//回收所有的子进程
    }
    close(fd[0]);
    close(fd[1]);
    return 0;
}

operation result

3. Famous pipeline

features

  1. Allows unrelated processes to communicate.
  2. Named pipes can be indicated by pathnames and are visible on the file system, but their contents are stored in memory.
  3. Well-known pipes for file IO operations
  4. FIFO
  5. The lseek() operation is not supported.

functional interface

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

Function: Create a famous pipeline

Parameters: filename: name of the pipe file

mode: permission

Return value: Success: 0

Fail: -1, and set errno number

Note how errors are handled:

If the error is file exist, pay attention to add judgment, such as: if ( errno == EEXIST )

Precautions

  1. Write-only mode, write blocking until another process opens the read
  2. Read-only mode, read blocking until another process opens the write
  3. Readable and writable, if there is no data in the pipeline, read blocking.

4. Summary

The difference between named pipes and unnamed pipes

nameless pipe

famous pipeline

scenes to be used

kinship

unrelated process

features

half duplex

fixed read and write

Treated as a special file, operated through file IO

Visible in the file system, data stored in memory

file IO operation

Does not support lseek() operation, follows first-in first-out

function

pipe()

Direct read, write

mkfifo()

Open first, then read and write

Read and write characteristics

When the unnamed pipe has no data, read blocking

When the unnamed pipe is full of 64k, write blocking

The read end is closed, continuing to write data will cause the pipe to break

Write-only mode, write blocking until another process opens the read

Read-only mode, read blocking until another process opens the write

Readable and writable, when there is no data in the pipeline, read blocking

Guess you like

Origin blog.csdn.net/m0_68672255/article/details/130394689