interprocess communication

interprocess communication

Interprocess communication is the dissemination or exchange of information between different processes, so what medium exists between different processes that can be accessed by both parties? The user space of the process is independent of each other and generally cannot access each other, the only exception is the shared memory area. However, the system space is a "public space", so the kernel can obviously provide such conditions. Beyond that, that's a peripheral that both parties can access. In this sense, two processes can of course also exchange information through ordinary files on disk, or through certain entries and records in the "registry" or other database. This is also a means of inter-process communication in a broad sense, but this is generally not counted as "inter-process communication".

Purpose

Data transfer: A process needs to send its data to another process.

Resource sharing: The same resources are shared among multiple processes.

Notification events: A process needs to send a message to another or another group of processes to notify him that some event has occurred (such as to notify the parent process when a process terminates).

Process control: Some processes want to completely control the execution of another process (such as the debug process). At this time, the controlling process hopes to intercept all traps and exceptions of another process, and be able to know its state changes in time.

main classification

Pipes: anonymous pipes, named pipes.

System V IPC: System V message queue, System V shared memory, System V semaphore.

POSIX IPC: message queues, shared memory, semaphores, mutexes, condition variables, read-write locks.

pipeline

Pipes are the oldest form of interprocess communication in Unix.

We call a stream of data from one process to another a pipe.


anonymous pipe

#include<unistd.h>

Function: Create an unnamed pipe.

Prototype: int pipe(int fd[2]);

Parameters: fd: array of file descriptors, where fd[0] represents the read end and fd[1] represents the write end

Return value: 0 for success, and an error code for failure.


Code: read data from keyboard, write to pipe, read pipe, write to screen

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
int main(void){
int fds[2];
char buf[100];
int len;
if(pipe(fds) == -1){
perror("make pipe"),exit(1);
}
//read from stdin
while(fgets(buf,100,stdin)){
len  = strlen(buf);
//write into pipe
if(write(fds[1],buf,len) != len){
perror("write to pipe");
break;
}
memset(buf,0x00,sizeof(buf));
//read from pipe
if((len = read(fds[0],buf,100)) == -1){
perror("read from pipe");
break;
}
//write to stdout
if(write(1,buf,len) != len){
perror("write to stdout");
break;
}
}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324685662&siteId=291194637