Linux Process Communication

Source: Internet
Author: User

I. Shared Memory:

System Call: shmget (); When shmget () creates a new shared memory, it returns an identifier of the shmid_ds data structure that can be used to reference the shared memory.

Prototype: int shmget (key_t key, int size, int shmflg );

Returned value: If successful, the shared memory segment identifier is returned.

If it fails,-1 is returned.

System Call: shmat (); map the shared memory area to your own process.

Prototype: int shmat (INT shmid, char * shmadddr, int shmflg );

Returned value: If successful, the shared memory segment is returned to the address in the process.

If it fails,-1 is returned.

System Call: shmdt (); when a process no longer needs to share a memory segment, it will remove the memory segment from other address spaces.

Prototype: int shmdt (char * shmaddr );

Returned value:-1 is returned if the request fails.

Instance code: shmadd. c

# Include <sys/types. h> # include <sys/IPC. h> # include <sys/SHM. h> # include <stdio. h> # include <stdlib. h> # define bufsz 2048int main () {int shmid; char * shmadd; If (shmid = shmget (ipc_private, bufsz, 0666) <0) {perror ("shmget"); exit (1);} else printf ("created shared-memory: % d \ n", shmid ); system ("IPCS-M");/* The IPCS command writes some information about the communication facilities between active processes to the standard output. */If (shmadd = shmat (shmid, 0, 0) <(char *) 0) {perror ("shmat"); exit (1 );} else printf ("attached shared-memory \ n"); System ("IPCS-M"); If (shmdt (shmadd) <0) {perror ("shmdt"); exit (1);} else printf ("deleted shared-memory \ n"); System ("IPCS-M "); exit (0 );}

Ii. Message Queue:

A message queue is a linked list of messages. It allows one or more processes to write messages to it and one or more processes to read messages from it. It has certain FIFO features, but can implement instant query of messages. These messages exist in the kernel and are identified by the queue ID.

The implementation of Message Queue includes four operations: Creating and opening a queue, adding a message, reading a message, and controlling a message queue.

Int msgget (key_t key, int flag): Creates and opens a queue. The number of messages is limited by the system.

Int msgsnd (INT msqid, struct msgbuf * msgp, size_t msgsz, int flag): Add a message to the end of the message queue.

Int msgrcv (INT msqid, struct msgbuf * msgp, size_t msgsz, long msgtyp, int flag): reads a message and removes it from the message queue.

Int msgctl (INT msqid, int cmd, struct msqid_ds * BUF): Controls message queues.

Instance code msg. c

#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#define BUFSZ 512struct message{  long msg_type;  char msg_text[BUFSZ];};int main(){  int qid;  key_t key;  int len;  struct message sndmsg,rcvmsg;    if((key=ftok(".","a"))==-1)  {   perroe("ftok");      exit(1);   }   if((qid=msgget(key,IPC_CREAT|0666))==-1)   {      perror("msgget");      exit(1);    }   printf("opened queue %d\n",qid);   puts("Please enter the message to queue:");   if((fgets((&sndmsg)->msg_text,BUFSZ,stdin))==NULL)   {     puts("no message");     exit(1);    }    sndmsg.msg_type=getpid();    len=strlen(sndmsg.msg_text);    if((msgsnd(qid,&sndmsg,len,0))<0)     {       perror("message posted");       exit(1);      }      if((msgrcv(qid,&rcvmsg,BUFSZ,0,0)<0)      {        perror("msgrcv");        exit(1);       }       printf("message is :%s\n",(&rcvmsg)->msg_text);       if((msgctl(qid,IPC_RMID,NULL))<0)       {         perror("msgctl");         exit(1);        }        exit(0); }


3. Pipelines

To create a simple pipeline, you can use the system to call pipe (). It accepts a parameter, that is, an array containing two integers. If the system call is successful, this array includes two file descriptors used by the pipeline. After creating an MPS queue, a new process is generated.

System Call: pipe ();

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

Note: FD [0] is used to read the MPs queue, and FD [1] is used to write data to the MPs queue.

One pipe is half-duplex.

Pipeline instance code:

# Include <unistd. h> # include <sys/types. h> # include <errno. h> # include <stdio. h> # include <stdlib. h> int main () {int pipe_fd [2];/* pipeline descriptor */pid_t PID;/* define process ID */Char buf_r [100]; /* read string */char * p_wbuf;/* write string pointer */INT r_num; memset (buf_r, 0, sizeof (buf_r )); /* clear all data in the buf_r character array to 0 */If (pipe (pipe_fd) <0) {printf ("pipe create error \ n"); Return-1 ;} /* parent process write, sub-process read */If (pid = fork () = 0)/* in the sub-process created by fork () */{printf ("\ N"); close (pipe_fd [1]);/* write pipeline descriptor close */sleep (2 ); /* sleep for 2 seconds */If (r_num = read (pipe_fd [0], buf_r, 100)> 0) /* read 100 bytes in the pipeline descriptor of pipe_fd [0] and put them into buf_r */{printf ("% d numbers read from the pipe is % s \ n ", r_num, buf_r);} Close (pipe_fd [0]);/* write pipeline descriptor close */exit (0);/* exit */} else if (pid> 0) {close (pipe_fd [0]);/* close the read pipeline descriptor */If (write (pipe_fd [1], "hello", 5 )! =-1) printf ("parent write1 success! \ N "); If (write (pipe_fd [1]," pipe ", 5 )! =-1) printf ("parent write2 success! \ N "); close (pipe_fd [1]; sleep (3); waitpid (PID, null, 0); exit (0 );}}

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.