Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The way Linux communicates between processes

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "the way of Linux inter-process communication". In the daily operation, I believe that many people have doubts about the way of Linux inter-process communication. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "Linux inter-process communication". Next, please follow the editor to study!

Another way of communicating between processes is explained below, using shared memory.

What is shared memory

As the name implies, shared memory allows two unrelated processes to access the same logical memory. Shared memory is a very efficient way to share and transfer data between two running processes. Shared memory between different processes is usually arranged as the same piece of physical memory. Processes can connect the same piece of shared memory to their own address space, and all processes can access addresses in shared memory as if they were memory allocated by the C language function malloc. If a process writes data to shared memory, the changes immediately affect any other process that can access the same segment of shared memory.

Special reminder: shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from reading it until * * processes finish writing to shared memory. So we usually need to use other mechanisms to synchronize access to shared memory, such as semaphores mentioned earlier. For more information about semaphores, you can refer to another of my articles: Linux interprocess communication-- using semaphores

Second, the use of shared memory

Like semaphores, a set of functional interfaces are provided in Linux for using shared memory, and interfaces that use shared coexistence are very similar to semaphores and are simpler than interfaces that use semaphores. They are declared in the header file sys/shm.h.

1. Shmget function

This function is used to create shared memory, and its prototype is:

[cpp] view plain copy int shmget (key_t key, size_t size, int shmflg)

* parameters. Like the semaphore semget function, the program needs to provide a parameter key (non-0 integer), which effectively names the shared memory segment. When the shmget function succeeds, it returns a shared memory identifier (non-negative integer) related to key for subsequent shared memory functions. Call failure returns-1.

Unrelated processes can access the same shared memory through the return value of this function, which represents a resource that the program may use. The program's access to all shared memory is indirect. The program first calls the shmget function and provides a key, and then the system generates a corresponding shared memory identifier (the return value of the shmget function). Only the shmget function directly uses the signal key. All other semaphore functions use the semaphore identifier returned by the semget function.

The second parameter, size, specifies the amount of memory to be shared in bytes

The third parameter, shmflg is the permission flag, and its function is the same as the mode parameter of the open function. If you want to create it when the shared memory identified by key does not exist, you can do or operate with IPC_CREAT. The permission flag for shared memory is the same as the read and write permissions for files, for example, 0644, which allows shared memory created by one process to be read and written to shared memory by processes owned by the memory creator. at the same time, processes created by other users can only read shared memory.

2. Shmat function

* * after the shared memory is created, it cannot be accessed by any process. The function shmat is used to start the access to the shared memory and connect the shared memory to the address space of the current process. Its prototype is as follows:

[cpp] view plain copy void * shmat (int shm_id, const void * shm_addr, int shmflg)

* parameters. Shm_id is the shared memory identity returned by the shmget function.

The second parameter, shm_addr, specifies that the shared memory connects to the address location in the current process, which is usually empty, which means that the system is allowed to choose the address of the shared memory.

The third parameter, shm_flg, is a set of flag bits, usually 0.

A pointer to shared memory is returned when the call is successful, and-1 is returned if the call fails.

3. Shmdt function

This function is used to separate shared memory from the current process. Note that detaching shared memory does not delete it, it just makes it no longer available to the current process. Its prototype is as follows:

[cpp] view plain copy int shmdt (const void * shmaddr)

The parameter shmaddr is the address pointer returned by the shmat function, which returns 0 on success and-1 on failure.

4. Shmctl function

Like the semaphore's semctl function, it is used to control shared memory, and its prototype is as follows:

[cpp] view plain copy int shmctl (int shm_id, int command, struct shmid_ds * buf)

* parameters. Shm_id is the shared memory identifier returned by the shmget function.

The second parameter, command, is the action to be taken, which can take the following three values:

IPC_STAT: sets the data in the shmid_ds structure to the current associated value of shared memory, that is, overwrites the value of shmid_ds with the current associated value of shared memory.

IPC_SET: if the process has sufficient permissions, set the current associated value of the shared memory to the value given in the shmid_ds structure

IPC_RMID: delete shared memory segment

The third parameter, buf, is a structure pointer that points to the shared memory mode and the structure of access permissions.

The shmid_ds structure consists of at least the following members:

[cpp] view plain copy struct shmid_ds {uid_t shm_perm.uid; uid_t shm_perm.gid; mode_t shm_perm.mode;}

Third, use shared memory for interprocess communication

Having said so much, it is time for actual combat again. Here are two unrelated processes to illustrate how processes communicate through shared memory. One of the files, shmread.c, creates shared memory and reads the information in it, while the other file, shmwrite.c, writes data to shared memory. In order to facilitate the operation and unify the data structure, the same data structure is defined for the two files, which is defined in the file shmdata.c. The written in the structure shared_use_st serves as a readable or writable flag, non-0: readable, 0 means writable, and text is a file in memory.

The source code for shmdata.h is as follows:

[cpp] view plain copy # ifndef _ SHMDATA_H_HEADER # define _ SHMDATA_H_HEADER # define TEXT_SZ 2048 struct shared_use_st {int written;// as a flag, non-0: readable, 0: writable char text [text _ SZ]; / / record written and read text}; # endif

The source file shmread.c has the following source code:

[cpp] view plain copy # include # include "shmdata.h" int main () {int running = 1 / the flag of whether the program continues to run void * shm = NULL;// the original first address of shared memory allocated struct shared_use_st * shared;// points to shm int shmid / / shared memory identifier / / create shared memory shmid = shmget ((key_t) 1234, sizeof (struct shared_use_st), 0666 | IPC_CREAT); if (shmid = =-1) {fprintf (stderr, "shmget failed\ n"); exit (EXIT_FAILURE) } / / Connect shared memory to the address space of the current process shm = shmat (shmid, 0,0); if (shm = = (void*)-1) {fprintf (stderr, "shmat failed\ n"); exit (EXIT_FAILURE);} printf ("\ nMemory attached at% X\ n", (int) shm) / / set shared memory shared = (struct shared_use_st*) shm; shared- > written = 0 While (running) / / read data in shared memory {/ / No process sets data to shared memory there is data to read if (shared- > written! = 0) {printf ("You wrote:% s", shared- > text); sleep (rand () 3) / / after reading the data, set written to make the shared memory segment writable shared- > written = 0; / / enter end and exit the loop (program) if (strncmp (shared- > text, "end", 3) = = 0) running = 0 } else// has other processes writing data and cannot read data sleep (1);} / / detach shared memory from the current process if (shmdt (shm) = =-1) {fprintf (stderr, "shmdt failed\ n"); exit (EXIT_FAILURE) } / / remove shared memory if (shmctl (shmid, IPC_RMID, 0) =-1) {fprintf (stderr, "shmctl (IPC_RMID) failed\ n"); exit (EXIT_FAILURE);} exit (EXIT_SUCCESS);}

The source file shmwrite.c has the following source code:

[cpp] view plain copy # include # include "shmdata.h" int main () {int running = 1; void * shm = NULL; struct shared_use_st * shared = NULL; char buffer [BUFSIZ + 1]; / / text int shmid used to save input / / create shared memory shmid = shmget ((key_t) 1234, sizeof (struct shared_use_st), 0666 | IPC_CREAT); if (shmid = =-1) {fprintf (stderr, "shmget failed\ n"); exit (EXIT_FAILURE) } / / Connect shared memory to the address space of the current process shm = shmat (shmid, (void*) 0,0); if (shm = = (void*)-1) {fprintf (stderr, "shmat failed\ n"); exit (EXIT_FAILURE);} printf ("Memory attached at% X\ n", (int) shm) / / set shared memory shared = (struct shared_use_st*) shm; while (running) / / write data to shared memory {/ / data has not been read, wait for the data to be read, cannot write text while (shared- > written = = 1) {sleep (1) to shared memory Printf ("Waiting...\ n");} / / write data to shared memory printf ("Enter some text:"); fgets (buffer, BUFSIZ, stdin); strncpy (shared- > text, buffer, TEXT_SZ); / / after writing the data, set written to make the shared memory segment readable shared- > written = 1 / / enter end, exit loop (program) if (strncmp (buffer, "end", 3) = = 0) running = 0;} / / detach shared memory from the current process if (shmdt (shm) = =-1) {fprintf (stderr, "shmdt failed\ n"); exit (EXIT_FAILURE) } sleep (2); exit (EXIT_SUCCESS);}

Let's take a look at the results of the operation:

Analysis:

1. The program shmread creates shared memory and connects it to its own address space. A structure struct_use_st is used at the beginning of the shared memory. There is a flag written in this structure. When other processes write data to it in shared memory, the written in shared memory is set to 0 and the program waits. When it is not 0, it means that no process is writing data to the shared memory, the program reads the data from the shared memory and outputs it, and then resets the written in the shared memory to 0 so that it can be written by the shmwrite process.

2. The program shmwrite acquires shared memory and connects to its own address space. Check whether the written in the shared memory is 0, if not, it means that the data in the shared memory has not been finished, wait for other processes to finish reading, and prompt the user to wait. If the written of the shared memory is 0, which means that no other process is reading the shared memory, the user is prompted for text, and the written in the shared memory is set to 1 again, indicating that the write is complete, and other processes can read the shared memory.

IV. Discussion on the security of the previous example

This program is not secure, and problems occur when multiple programs read and write data to shared memory at the same time. You may think that you can change the way written is used. For example, a process can write data to shared memory only when written is 0, and when a process can read it only when written is not 0, add 1 to written and subtract 1 after reading. This is a bit like a read-write lock in a file lock. At first glance, it seems to work. But none of this is an atomic operation, so this is not possible. Imagine that when written is 0, if two processes access shared memory at the same time, they will find that written is 0, so both processes write to it, obviously not. When written is 1, the same is true when two processes read shared memory at the same time, and when both processes finish reading, written becomes-1.

In order for the program to be executed safely, there must be a process synchronization system to ensure that the operation entering the critical area is atomic. For example, you can use the semaphores mentioned earlier to synchronize processes. Because the operation of semaphores is atomic.

5. Advantages and disadvantages of using shared memory

1. Advantages: we can see that it is very convenient to use shared memory for inter-process communication, and the interface of the function is also simple. Data sharing also makes the data between processes not to be transmitted, but directly accesses memory, which also speeds up the efficiency of the program. At the same time, it does not require the communication process to have a certain parent-son relationship like anonymous pipes.

2. Disadvantages: shared memory does not provide synchronization mechanism, which makes us often use other means to carry out inter-process synchronization when we use shared memory for inter-process communication.

At this point, the study on "the way of Linux inter-process communication" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report