Linux Process Communication 20160720

Source: Internet
Author: User
Tags new set random seed semaphore

Long time no update, today mainly talk about the Linux process communication, follow-up Linux updates should be slow, because recently in the Java and Android knowledge, follow-up will be based on learning results to share the update of Java and Android knowledge ~

Linux process communication knowledge, it is recommended to refer to the "UNIX Environment Advanced Programming" This book, here is just a summary:

1. Threads: Communication between child threads in a process, memory (variables) between threads is shared, and shared memory is a global variable, so be aware of mutual exclusion

2. Process: Communication between processes must be implemented with the help of the kernel:

1) Pipe:

(nameless) pipeline, can only be used for parent-child interprocess communication: one-way (read at the end of the write), the fork is the child process, the corresponding operation Fock for the parent process

The array that creates the pipe is two sizes, one for writing to close the read at the same time, one for reading and closing write, two integers for writing, one for reading

Example code:

Nameless pipes are created by the pipe () function:

#include <unistd.h>

int pipe (int filedis[2]);

Parameter Filedis returns two file descriptor: filedes[0] Open for Read, filedes[1] for write. The output of filedes[1] is the input of filedes[0]. The following example demonstrates how to communicate between parent and child processes.

#define INPUT 0

#define OUTPUT 1

void Main () {

int file_descriptors[2];

/* Define child process number */

pid_t pid;

Char buf[256];

int returned_count;

/* Create a nameless pipe */

Pipe (file_descriptors);

/* Create Child process */

if (PID = fork ()) = =-1) {

printf ("Error in fork/n");

Exit (1);

}

/* Execute child process */

if (PID = = 0) {

printf ("In the spawned (child) process.../n");

/* Child process writes data to the parent process, closes the read-side of the pipeline */

Close (File_descriptors[input]);

Write (File_descriptors[output], "test data", strlen ("test Data"));

Exit (0);

} else {

/* Execute Parent Process */

printf ("In the Spawning (parent) process.../n");

/* The parent process reads the data written by the child process from the pipeline, closing the write end of the pipeline */

Close (File_descriptors[output]);

Returned_count = Read (File_descriptors[input], buf, sizeof (BUF));

printf ("%d bytes of data received from spawned process:%s/n",

Returned_count, BUF);

}

}

2) Named pipe:

(well-known) pipeline: for unrelated processes, you need to create a FIFO file (a file with a name that is used for communication)

Under the Linux system, a well-known pipeline can be created in two ways: command-line mode Mknod system calls and function Mkfifo. Both of the following paths generate a well-known pipeline named Myfifo in the current directory:

Mode one: Mkfifo ("Myfifo", "RW");

Mode two: Mknod Myfifo p

Once a named pipeline is generated, it can be manipulated using generic file I/O functions such as open, close, read, write, and so on. Here is a simple example, assuming that we have created a well-known pipeline named Myfifo.

/* Process one: Read the famous pipe */

#include <stdio.h>

#include <unistd.h>

void Main () {

FILE * IN_FILE;

int count = 1;

Char buf[80];

In_file = fopen ("Mypipe", "R");

if (In_file = = NULL) {

printf ("Error in fdopen./n");

Exit (1);

}

while ((count = Fread (buf, 1, in_file)) > 0)

printf ("Received from pipe:%s/n", buf);

Fclose (In_file);

}

/* Process two: Write a famous pipeline */

#include <stdio.h>

#include <unistd.h>

void Main () {

FILE * OUT_FILE;

int count = 1;

Char buf[80];

Out_file = fopen ("Mypipe", "w");

if (Out_file = = NULL) {

printf ("Error opening pipe.");

Exit (1);

}

sprintf (BUF, "This was test data for the named pipe example/n");

Fwrite (buf, 1, out_file);

Fclose (Out_file);

}

3) Message Queuing:

Message Queuing is used to run interprocess communication on the same machine, which is similar to a pipeline and is a queue used to hold messages in the system kernel, which appears as a list of messages in the system kernel. The structure of the nodes in the message list is declared with MSG.

In fact, it is a gradually phased out of communication, can be used to replace it with a stream pipeline or a socket interface, so the method is no longer explained, it is recommended that readers ignore this way.

4) Signal Volume:

Semaphores are also called semaphores, which are used to coordinate data objects between different processes, and the most important application is interprocess communication in the previous section of shared memory mode. Essentially, a semaphore is a counter that is used to record access to a resource, such as shared memory. In general, in order to get a shared resource, the process needs to do the following:

(1) test the semaphore that controls the resource.

(2) If the value of this semaphore is positive, the resource is allowed to be used. The process will reduce the semaphore by 1.

(3) If the semaphore is 0, the resource is currently unavailable, the process goes to sleep until the semaphore value is greater than 0, the process is awakened, and the step is transferred (1).

(4) When the process no longer uses a semaphore-controlled resource, the semaphore value is added 1. If there is a process waiting for this semaphore at this time, the process is awakened.

The status of the semaphore is maintained by the Linux kernel operating system and not by the user process. We can see the definition of each structure that the kernel uses to maintain semaphore status from the/usr/src/linux/include/linux/sem.h file. A semaphore is a collection of data that a user can use individually for each element of the collection. The first function to invoke is Semget, which is used to obtain a semaphore ID.

struct SEM {

Short sempid;/* pid of the last Operaton */

ushort semval;/* Current Value */

ushort semncnt;/* num procs awaiting increase in Semval */

ushort semzcnt;/* num procs Awaiting semval = 0 */

}

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/sem.h>

int Semget (key_t key, int nsems, int flag);

Key is the keyword for the IPC structure that was previously spoken, and flag will decide in the future whether to create a new semaphore collection or to reference an existing semaphore collection. Nsems is the number of semaphores in the collection. If you are creating a new collection (typically in the server), you must specify Nsems, or if you are referencing an existing semaphore collection (typically in the client), specify Nsems as 0.

The SEMCTL function is used to manipulate the semaphore.

int semctl (int semid, int semnum, int cmd, Union semun Arg);

The different operations are implemented by the CMD parameter, which defines 7 different operations in the header file sem.h, which can be used as reference in the actual programming.

  

The SEMOP function automatically executes an array of operations on the semaphore set.

int semop (int semid, struct sembuf semoparray[], size_t nops);

Semoparray is a pointer to an array of semaphore operations. NOPS Specifies the number of operations in the array.

Below, let's look at a specific example, it creates a specific IPC structure of the keyword and a semaphore, establishes the index of this semaphore, modifies the value of the semaphore to which the index points, and finally clears the semaphore. In the following code, the function Ftok generates the only IPC keyword we said above.

#include <stdio.h>

#include <sys/types.h>

#include <sys/sem.h>

#include <sys/ipc.h>

void Main () {

key_t Unique_key; /* Define an IPC keyword */

int id;

struct SEMBUF lock_it;

Union Semun Options;

int i;

Unique_key = Ftok (".", ' a '); /* Generate the keyword, the character ' A ' is a random seed */

/* Create a new set of semaphores */

id = semget (unique_key, 1, ipc_creat | Ipc_excl | 0666);

printf ("Semaphore id=%d/n", id);

Options.val = 1; /* Set Variable values */

Semctl (ID, 0, setval, options); /* Set the semaphore for index 0 */

/* Print out the value of the semaphore */

i = semctl (ID, 0, getval, 0);

printf ("Value of semaphore at index 0 is%d/n", i);

/* Reset semaphore below */

Lock_it.sem_num = 0; /* Set which semaphore */

Lock_it.sem_op =-1; /* Define ACTION */

LOCK_IT.SEM_FLG = ipc_nowait; /* Operation mode */

if (Semop (ID, &lock_it, 1) = =-1) {

printf ("Can not lock semaphore./n");

Exit (1);

}

i = semctl (ID, 0, getval, 0);

printf ("Value of semaphore at index 0 is%d/n", i);

/* Clear the semaphore */

Semctl (ID, 0, ipc_rmid, 0);

}

5) Shared Memory: high efficiency , attention to mutex issues (can use semaphores to achieve mutual exclusion, or use locks)

The main use of shared memory, high efficiency, a put data into a kernel memory (shared memory), B directly to read it.

Under the Linux system, the common way is through the SHMXXX function family to realize the storage using the shared memory.

The first function to be used is shmget, which obtains a shared storage identifier.

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

int Shmget (key_t key, int size, int flag);

When shared memory is created, the rest of the process can call Shmat () to connect it to its own address space.

void *shmat (int shmid, void *addr, int flag);

Shmid the shared storage identifier returned for the Shmget function, the addr and flag parameters determine how the address of the connection is determined, the return value of the function is the actual address to which the process data segment is connected, and the process can read and write to the process.

Three more similar:

Create/Get: (a Create B Get) use function (Message Queuing: Msgget), (semaphore: Semget), (Shared Memory: shmget), parameters are divided into create/get

Written by: Msgsnd, Semop,

READ: Msgrcv,semop

All five of these methods refer to the same machine

6) network communication, suitable for different machines, and the same machine (such as a process to the B process, less than the hardware at the bottom of the B, speed is also fast) can

Good portability, basic support, so there are no special requirements, such as the requirement is very high or a parent-child process situation, the general use of network communication

See the previous article Socket socket programming with detailed instructions

Maximum network communication

7) signal, mainly through kill to send, but to know the other side of the PID, so beforehand can be agreed, id put to which file, then the other side to read

8) Flow pipe ...

Linux Process Communication 20160720

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.