Linux Network Programming-inter-process communication (I), linux Network Programming
Introduction to inter-process communication (from Linux Network Programming p85)
AT&T introduced several new process communication methods in UNIX System V, namely MessageQueues, semaphores, and shared memory, collectively referred to as System v ipc. They are widely used in Linux programming.
A notable feature of System v ipc is that its specific instance appears in the kernel in the form of an object, which is called an IPC object. Each IPC object has a unique identifier in the system kernel. The identifier kernel can correctly reference the specified IPC object .. Note that the uniqueness of an identifier is valid only in each type of IPC object. For example, a message queue and a semaphore identifier may be the same, but there will never be two Message Queues with the same identifier.
Identifiers are used only in the kernel, and IPC objects are accessed by key in the program. Like the IPC object identifier, the keyword must also be unique. In addition, to access the same IPC object, the Server and Client must use the same keyword. Therefore, how to construct a new keyword so that it does not conflict with an existing keyword and ensure that the keywords used by the Server and Client are the same is the first problem to be solved when an IPC object is created. (For details, refer to the msg communication below)
Communication methods include: half-duplex pipe, named pipe fifo, message queue, semaphore, shared inner, socket, etc. The following describes one by one:
① Half duplex pipe:
Int pipe (int filedes [2]);
A pipeline is a mechanism for interlinking standard input and output between two processes.
Pipeline used in linux commands |: ls-l | grep *. c // display file (input end)-(|)-(output end)> find the end file of. c
Implementation: Because of half-duplex, only one input and one output can be achieved, rather than two-way communication. So: The implementation is to connect the process through the pipeline, open the description of the read file at one end, and open the description of the Write File at one end.
// The nature of the pipeline is that the output of one process serves as the input of another process. // you can disable the read end of one process as the input. // The write end of another process is disabled, reads data and receives the data as the output end of the MPs queue // FIFO named MPs queue // file system, named MPs queues exist in special files. // different processes can share data using named MPs queues. // named MPs queues are blocked all the time, it must be shown that the channel connected to the pipeline is established through open # include <stdio. h> # include <stdlib. h> # include <string. h> # include <unistd. h> # include <sys/types. h> int main () {int result = 1; int fd [2]; pid_t pid; int * write_fd = & fd [1]; // Write File description int * read_fd = & fd [0]; // Read File description int nbytes; char str [] = "Pipeline, Hello \ n "; char readBuffer [80]; memset (readBuffer, 0, sizeof (readBuffer); result = pipe (fd ); // create pipeline if (-1 = result) {printf ("pipeline creation failed! \ N "); return-1;} pid = fork (); // if (-1 = pid) {printf (" fork failed "); return-1;} if (0 = pid) // The sub-process closes the read end and writes the string {close (* read_fd); result = write (* write_fd, str, strlen (str); printf ("write % d Data \ n", result);} else // The parent process closes the write end and reads data {close (* write_fd ); nbytes = read (* read_fd, readBuffer, sizeof (readBuffer); printf ("% d data received, content: % s", nbytes, readBuffer );} return 0 ;}
② Named Pipe
Int mkfifo (const char * pathname, mode_t mode );
Similar to a common pipeline,
A. exists in the file system as a special file of the device
B. Data can be shared between different processes through named Pipelines
Operations are different from common pipelines: FIFO must explicitly establish a channel connected to the pipeline through open, and is always in the blocking status
③ Message Queue
Message Queue is an internal linked list of the kernel address space, which transmits content between processes through the kernel. Each message queue is identified by a unique IPC identifier. Different queues are relatively independent.
//file: msg.h
/* message buffer for msgsnd and msgrcv calls */struct msgbuf { __kernel_long_t mtype; /* type of message */ char mtext[1]; /* message text */};/* Obsolete, used only for backwards compatibility and libc5 compiles */struct msqid_ds { struct ipc_perm msg_perm; struct msg *msg_first; /* first message on queue,unused */ struct msg *msg_last; /* last message in queue,unused */ __kernel_time_t msg_stime; /* last msgsnd time */ __kernel_time_t msg_rtime; /* last msgrcv time */ __kernel_time_t msg_ctime; /* last change time */ unsigned long msg_lcbytes; /* Reuse junk fields for 32 bit */ unsigned long msg_lqbytes; /* ditto */ unsigned short msg_cbytes; /* current number of bytes on queue */ unsigned short msg_qnum; /* number of messages in queue */ unsigned short msg_qbytes; /* max number of bytes on queue */ __kernel_ipc_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_ipc_pid_t msg_lrpid; /* last receive pid */};
// Filename
/* Obsolete, used only for backwards compatibility and libc5 compiles */struct ipc_perm {_ kernel_key_t key; // key value used by the msgget () function _ kernel_uid_t uid; // user UID _ kernel_gid_t gid; // user GID _ kernel_uid_t cuid; // creator UID _ kernel_gid_t cgid; // creator GID _ kernel_mode_t mode; // permission unsigned short seq; // serial number };
Message Queue in Kernel
Note: The list_head structure forms a linked list. The m_list in the msg_msg structure forms a linked list for messages. During searching and insertion, the m_list field is offset to locate the position.
Related functions:
Key value construction key_t ftok (const char * pathname, int proj_id );
Get the message int msgget (key_t key, int msgflg );
Send message int msgsnd (int msqid, const void * msgp, size_t msgsz, int msgflg );
Receive message ssize_t msgrcv (int msqid, void * msgp, size_t msgsz, long msgtype, int msgflg );
Message control int msgctl (int msqid, int cmd, struct msqid_ds * buf); // send the cmd command to the kernel to determine the operation to be performed
A simple example
④ Semaphores
A semaphore is a counter used to control access to resources shared by multiple processes. Common lock mechanism (producer and consumer model is a typical use)
Semaphore Structure
// Filename sys/sem. h
/* Arg for semctl system CILS. */union semun {int val;/* value for SETVAL */struct semid_ds * buf;/* buffer for IPC_STAT & IPC_SET */unsigned short * array; /* Array Structure */struct seminfo * _ buf;/* internal semaphore structure */void * _ pad ;};
Related functions
Create a semaphore int semget (key_t key, int nsems, int semflg );
// The key is from ftok ()
Semaphore operation function int semop (int semid, struct sembuf * sops, unsigned nsops );
// The P and V Operations of semaphores are completed by sending commands to the established semaphores
Control semaphore Parameters
Int semctl (int semid, int semnum, int cmd ,.....);
// Used to execute control operations on the semaphore set
#include<stdio.h>#include<unistd.h>#include<sys/ipc.h>#include<sys/sem.h>#include<sys/types.h>typedef int sem_t;union semun{ int val; struct semid_ds * buf; unsigned short *array;}arg;sem_t CreateSem(key_t key, int value){ union semun sem; sem_t semid; sem.val = value; semid = semget(key,0,IPC_CREAT); if(-1 == semid) { printf("create semaphore error\n"); return -1; } semctl(semid,0,SETVAL,sem); return semid;}int Sem_P(sem_t semid){struct sembuf sops = {0,+1,IPC_NOWAIT};return (semop(semid,&sops,1));}int Sem_V(sem_t semid){ struct sembuf sops = {0,-1,IPC_NOWAIT}; return (semop(semid,&sops,1));}void SetvalueSem(sem_t semid , int value){ union semun sem; sem.val = value; semctl(semid,0,SETVAL,sem);}int GetvalueSem(sem_t semid){ union semun sem; return semctl(semid,0,GETVAL,sem);}void DestroySem(sem_t semid){ union semun sem; sem.val = 0; semctl(semid,0,IPC_RMID,sem);}int main(){ key_t key; int semid; char i; int value = 0; key = ftok("/ipc/sem",'a'); semid = CreateSem(key,100); for( i = 0;i <= 3;++i) { Sem_P(semid); Sem_V(semid); } value = GetvalueSem(semid); DestroySem(semid); return 0;}
⑤ Shared memory (the quickest way) has no intermediate processes, pipelines, etc.
A communication mode between processes that share the memory area. Memory sharing is achieved by ing the memory segments between processes.
Related functions
Create the shared memory function int shmget (key_y key, size_t size, int shmflg );
Obtain the shared memory address void * shmat (int shmid, const void * shmaddr, int shmflg );
Delete the shared memory function int shmdt (const void * shmadddr );
Shared Memory Control Function int shmctl (int shmid, int cmd, struct shmid_ds * buf );
⑥ Signal
It is used to transmit asynchronous signals between one or more processes.
Related functions
Signal truncation sighandler signal (int signum, sighandler handler );
Sending signal int kill (pid_t pid, int sig );
Int raise (int sig );