[Linux] Process (vii)--Process communication

Source: Internet
Author: User
Tags message queue

Inter-process communication
One, pipe,
Limitations of Pipelines:
(1) Half-duplex, data can only flow in one Direction
(2) Pipelines are generally used only between processes that have a common ancestor, typically a pipeline is created by a process, and then the process calls the fork () function, which can then be used by the parent-child process
Pipeline creation:

[CPP]View Plaincopy
    1. #include <unistd.h>
    2. int pipe (int fileds[2]); //filedes[0] Open for reading, filedes[1] open for writing

Writing data to a pipeline that is not associated with a read process produces sigpipe, and the kernel's default action for Sigpipe is to exit the process, which is usually not what we expect to see, so we need to overload this signal processing method, signal (sigpipe,sig_ign);


Second, FIFO
FIFO is called a named pipe, unlike a pipe, a process that is not related to a FIFO can also exchange data
The FIFO is created in the following way

[CPP]View Plaincopy
    1. int Mkfifo (const char*pathname,mode_t mode);

After the FIFO is created, the general operation function of the file can be used for it, open close read Write, etc.
FIFO is used by multiple processes for write is common, so the synchronization between processes should be considered, and the data written by multiple write processes will not be interspersed. A: pipe_buf Specifies the size of the pipe buffer in the kernel, and the size of all write processes must be less than the size of pipe_buf
FIFO can be used for communication between client process and service process, how to ensure synchronization?
A: The service process creates a well-known FIFO to receive requests from the client process, then creates a response message for each client process to send a service process to the client process, based on the customer process ID, and the question is how the service process knows that the client process has exited?
The drawback of FIFO is that random access is not supported because both pipe and FIFO are first-in, first-out features


Three, Message Queuing
To view the Linux system shared memory and Message Queuing scenarios:

IPCs [-m|-q|-s]
-m outputs information about shared memory (GKFX)
-Q Output Information about information queue (message queue)
IPCRM command

Shared memory used to manually de-use Linux ~


Four, shared memory
The following shared memory is mostly from the following URLs click the Open link
Shared memory is suitable for larger datasets because it uses memory, supports fast random access, and is the fastest form of IPC shared memory is not partitioned in memory owned by a process; the memory of the process is always private.
Shm_open (): Creates a shared memory segment or connects to an existing named memory segment. This system call returns a file descriptor.
Shm_unlink (): Deletes a shared memory segment based on the file descriptor (Shm_open () returned). In fact, this memory segment is accessed until
It is deleted when all of its processes are exited, similar to deleting files in UNIX. However, after calling Shm_unlink () (usually called by the process that originally created the shared memory segment), the memory segment cannot be accessed by other processes.
Mmap (): Maps the shared memory segment to the memory of the process. This system call requires the file descriptor returned by Shm_open (), which returns a pointer to memory. (In some cases, you can also map the file descriptor of a generic file or another device to memory.) The implementation of Mmap is also based on the above principle, when using Mmap to map a file (or part of a file) to the address space of the process, and does not load the file data, but only in the process of the virtual address space to divide a block, marking the area for mapping to the file data region, The operation of the mmap is complete.
void* mmap (void * addr, size_t len, int prot, int flags, int fd, off_t offset)
Munmap (): The effect is opposite to mmap ().
Msync (): Used to synchronize shared memory segments with the file system-this technique is useful when mapping files to memory.
Steps to use shared memory:
The process of using shared memory is to create a memory segment with Shm_open (), set its size with write () or ftruncate (), map it to process memory with mmap (), and perform the actions required by other actors. When it is finished, the original process calls Munmap () and Shm_unlink (), and then exits.

Sample Program

[CPP]View Plaincopy
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/file.h>
  6. #include <sys/mman.h>
  7. #include <sys/wait.h>
  8. void Error_and_die (const char *msg) {
  9. Perror (msg);
  10. Exit (Exit_failure);
  11. }
  12. int main (int argc, char *argv[]) {
  13. int R;
  14. const Char *memname = "Sample";
  15. Const size_t region_size = sysconf (_sc_page_size);
  16. int fd = Shm_open (MemName, O_creat | O_trunc |  O_rdwr, 0666);
  17. if (fd = =-1)
  18. Error_and_die ("Shm_open");
  19. r = Ftruncate (FD, region_size);
  20. if (r! = 0)
  21. Error_and_die ("ftruncate");
  22. void *ptr = mmap (0, region_size, Prot_read |  Prot_write, map_shared, FD, 0);
  23. if (ptr = = map_failed)
  24. Error_and_die ("mmap");
  25. Close (FD);
  26. pid_t pid = fork ();
  27. if (pid = = 0) {
  28. U_long *d = (U_long *) ptr;
  29. *d = 0xdbeebee;
  30. Exit (0);
  31. }
  32. else {
  33. int status;
  34. Waitpid (PID, &status, 0);
  35. printf ("child wrote% #lx \ n", * (U_long *) ptr);
  36. }
  37. r = Munmap (PTR, region_size);
  38. if (r! = 0)
  39. Error_and_die ("Munmap");
  40. R = Shm_unlink (MemName);
  41. if (r! = 0)
  42. Error_and_die ("Shm_unlink");
  43. return 0;
  44. }


Here is another example program

Click to open link

[CPP]View Plaincopy
  1. /*-------------map_normalfile1.c-----------*/
  2. #include <sys/mman.h>
  3. #include <sys/types.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. typedef struct{
  7. Char name[4];
  8. int age;
  9. }people;
  10. Main (int argc, char** argv) //Map a normal file as shared mem:
  11. {
  12. int fd,i;
  13. People *p_map;
  14. Char temp;
  15. Fd=open (argv[1],o_creat| o_rdwr| o_trunc,00777);
  16. Lseek (FD,sizeof (people) *5-1,seek_set);
  17. Write (FD,"", 1);
  18. P_map = (people*) mmap (NULL,sizeof (people) *10,prot_read| Prot_write,
  19. map_shared,fd,0);
  20. Close (FD);
  21. temp = ' a ';
  22. For (i=0; i<10; i++)
  23. {
  24. temp + = 1;
  25. memcpy ((* (P_map+i)). Name, &temp,2);
  26. (* (P_map+i)). Age = 20+i;
  27. }
  28. printf ("Initialize over \ n");
  29. Sleep (10);
  30. Munmap (P_map, sizeof (people) *10);
  31. printf ( "Umap OK \ n");
  32. }
  33. /*-------------map_normalfile2.c-----------*/
  34. #include <sys/mman.h>
  35. #include <sys/types.h>
  36. #include <fcntl.h>
  37. #include <unistd.h>
  38. typedef struct{
  39. Char name[4];
  40. int age;
  41. }people;
  42. Main (int argc, char** argv) //Map a normal file as shared mem:
  43. {
  44. int fd,i;
  45. People *p_map;
  46. Fd=open (argv[1],o_creat| o_rdwr,00777);
  47. P_map = (people*) mmap (NULL,sizeof (people) *10,prot_read| Prot_write,
  48. map_shared,fd,0);
  49. For (i = 0;i<10;i++)
  50. {
  51. printf ( "name:%s Age%d;\n", (* (P_map+i)). Name, (* (P_map+i)). Age);
  52. }
  53. Munmap (P_map,sizeof (people) *10);
  54. }

Limitations of Shared Memory:

Click to open link

Normal size is 32M, can be changed by Shmmax ~

/proc/sys/kernel/shmmax




Five, signal
A soft interrupt signal (signal, also referred to as a signal) is used to notify the process that an asynchronous event has occurred. Processes can send soft interrupt signals to each other through system call kill.
A signal is simply used to notify a process of what has happened and does not pass any data to the process.
There is a soft interrupt signal field in the table entry for the process table, where each bit of the field corresponds to a signal that corresponds to the position bit when a signal is sent to the process. As you can see, the process can keep the different signals at the same time, but for the same signal, the process does not know how many have come before processing.
The signal processing functions are as follows

[CPP]View Plaincopy
    1. void (*signal (int signo,Void (*func) (int)))(int )

Examples such as the following

[CPP]View Plaincopy
    1. if (signal (SIGUSR1,SIG_USR) ==sig_err)
    2. printf ("Can not catch sig_usr1");

The Kill function is used to send a signal to a process or process group, and the Raise function allows the process to send a signal to itself

[CPP]View Plaincopy
    1. int Kill (pid_t pid,int signo);
    2. int raise (int signo);

The disadvantage of a signal is that it cannot be used to transmit data and is typically used to notify exceptions between processes


Six: Socket communication



Seven, file

A bit is can share a large amount of data, the disadvantage is that the share is slow, because it involves the disk read and write, disk speed than memory, and the file itself is not secure, some privileged users can delete files.

[Linux] Process (vii)--Process communication

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.