Linux Network Programming-interprocess communication (i)

Source: Internet
Author: User
Tags message queue semaphore

Introduction to Interprocess communication (excerpt from Linux network programming P85)

At/T introduces several new methods of process communication in UNIX System V, namely, Message Queuing (messagequeues), Semaphore (semaphores), and shared memory, collectively known as System v IPC. In Linux system programming, they have a wide range of applications.
A notable feature of the System V IPC is that its concrete instances are in the form of objects in the kernel, which we call IPC objects . Each IPC object has a unique identifier in the system kernel. The specified IPC object can be correctly referenced by the identifier kernel: It should be noted that the uniqueness of identifiers is only established within 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 through the keyword (key) in the program. as with the IPC object identifier, the keyword must also be unique. Also, to access the same IPC object, both the Server and the client must use the same keyword. Therefore, how to construct a new keyword to not conflict with existing keywords, and to ensure that the server and Client use the same keyword, is the first problem to solve when establishing an IPC object. (specifically in the MSG communication behind the detailed)

Communication methods are: half-duplex pipeline pipe, named pipe FIFO, Message Queuing, semaphore, shared, socket sockets, etc., the following describes:

① Half-duplex pipe:

int pipe (int filedes[2]);

Piping is a mechanism for interfacing standard input and output between two processes

Pipelines used in Linux commands | : Ls-l | grep *.c//Display file (Input)-(|) -(output)> Find. C End File

Implementation: Because of the half-duplex reason, so can only achieve a certain input, a section of output, but not two-way communication. So: implemented as, through the pipeline connection process, one end open read file description, one end open Write file description

//The nature of a pipeline is that the output of one process as input to another process//then we can close a process read to make it an input,//Another process closes the write end, reads the data, and receives the data as a pipe output//FIFO Named Pipes//in a file system, a named pipe is a special file in a way that exists//different processes can share data through named Pipes//Named pipes are always blocked and must be displayed through open to establish a channel connected to the pipeline#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<sys/types.h>intMain () {intresult =1; intfd[2];    pid_t pid; int*WRITE_FD = &fd[1];//Write File Description    int*READ_FD = &fd[0];//Read File Description        intnbytes; CharStr[] ="pipeline, hello \ n"; Charreadbuffer[ the]; memset (Readbuffer,0,sizeof(Readbuffer)); Result= Pipe (FD);//Creating Pipelines    if(-1==result) {printf ("Pipeline creation failed! \ n"); return-1; } PID= Fork ();//Process Creation Fork Program    if(-1==pid) {printf ("Fork Failed"); return-1; }    if(0==PID)//the child process closes the read end and writes the characters{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 the data{Close (*write_fd); Nbytes= Read (*read_fd,readbuffer,sizeof(Readbuffer)); printf ("%d data received with%s content", Nbytes,readbuffer); }    return 0;}

② Named Pipes

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

Similar to ordinary pipes, just

A. In the file system in the form of a device special file

B. Different processes can share data through named pipes

Operation differs from normal pipe: the FIFO must explicitly establish a channel connected to the pipe through open and always in a blocked state

③ Message Queuing

Message Queuing is the internal linked list of the kernel address space through which content is passed through the kernel across processes. Each message queue is identified by a unique IPC identifier, and the different queues are relatively independent.

  

//file:msg.h
/*message buffer for MSGSND and MSGRCV calls*/structmsgbuf {__kernel_long_t mtype; /*type of message*/ Charmtext[1];/*Message Text*/};/*Obsolete, used only for backwards compatibility and LIBC5 compiles*/structMsqid_ds {structIpc_perm msg_perm; structMSG *msg_first;/*First message on queue,unused*/ structMSG *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*/unsignedLongMsg_lcbytes;/*reuse junk fields for + bit*/unsignedLongMsg_lqbytes;/*ditto*/unsigned ShortMsg_cbytes;/*Current number of bytes on queue*/unsigned ShortMsg_qnum;/*Number of messages in queue*/unsigned ShortMsg_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
/**/struct ipc_perm{ __kernel_key_t key;  The function Msgget () uses the key value __kernel_uid_t uid;  User uid __kernel_gid_t GID;  User gid __kernel_uid_t cuid;  Creator uid __kernel_gid_t cgid;   Created by GID __kernel_mode_t mode;  Permission short seq; Serial number};

Message Queuing in the kernel

Note: The structure list_head form a linked list, the structure of the msg_msg in the M_list makes the message form a list, find, insert, offset to the m_list domain find location

Related functions:

Key value Construction key_t ftok (const char* pathname,int proj_id);

Gets the message int msgget (key_t key,int MSGFLG);

Send message int msgsnd (int msqid, const void * msgp,size_t msgsz,int MSGFLG);

Receive Messages 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 a cmd command to the kernel to determine what to do

A simple example

④ Signal Volume

A semaphore is a counter used to control access to resources shared by multiple processes. commonly used as a lock mechanism (producer consumer model is a typical use)

Semaphore structure

//filename sys/sem.h
/*ARG for SEMCTL system calls.*/Union Semun {intVal/*value for Setval*/ structSemid_ds *buf;/*buffer for Ipc_stat & Ipc_set*/unsigned Short*array;/*Array Structure*/ structSeminfo *__buf;/*internal structure of signal volume*/ void*__pad;};

Related functions

New semaphore int Semget (key_t key, int nsems, int semflg);

Key from Ftok ()

Semaphore operation function int semop (int semid,struct sembuf* sops, unsigned nsops);

The p,v operation of the semaphore is done by sending a command to the already established signal volume

Control semaphore parameters

int semctl (int semid, int semnum, int cmd,.....);

Used to perform control operations on semaphore sets

#include <stdio.h>#include<unistd.h>#include<sys/ipc.h>#include<sys/sem.h>#include<sys/types.h>typedefintsem_t;union semun{intVal; structSemid_ds *buf; unsigned Short*Array;} arg;sem_t Createsem (key_t key,intvalue)    {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); returnSemid;}intsem_p (sem_t semid) {structSembuf SOPs = {0,+1, ipc_nowait};return(Semop (Semid,&sops,1));}intSem_v (sem_t semid) {structSembuf SOPs = {0,-1, ipc_nowait}; return(Semop (Semid,&sops,1));}voidSetvaluesem (sem_t Semid,intvalue)    {Union Semun SEM; Sem.val=value; Semctl (Semid,0, Setval,sem);}intGetvaluesem (sem_t semid) {Union Semun sem; returnSemctl (Semid,0, Getval,sem);}voidDestroysem (sem_t semid) {Union Semun sem; Sem.val=0; Semctl (Semid,0, Ipc_rmid,sem);}intMain () {key_t key; intSemid; Chari; intValue =0; Key= Ftok ("/ipc/sem",'a'); Semid= Createsem (Key, -);  for(i =0; I <=3;++i) {sem_p (semid);        Sem_v (Semid); } Value=Getvaluesem (Semid);        Destroysem (Semid); return 0;}

⑤ shared memory (quickest method) No intermediate process, pipeline, etc.

An inter-process communication method that shares memory areas across multiple processes to enable memory sharing in ways that map memory segments across multiple processes.

Related functions

Create a shared memory function int Shmget (key_y key, size_t size, int shmflg);

Get 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

Used to pass asynchronous signals between one or more processes.

Related functions

Signal interception Sighandler Signal (int signum, Sighandler handler);

Send signal int Kill (pid_t pid, int sig);

int raise (int sig);

  

  

  

  

Linux Network Programming-interprocess communication (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.