Linux operating system analysis (10)

Source: Internet
Author: User

Abstract

In Linux, inter-process communication mechanisms mainly include: pipe FIFO, semaphores, messages, shared memory areas, and sockets. Programmers can choose based on their needs.


MPs queue

The pipeline is a buffer zone managed by the kernel, which is equivalent to a piece of paper we put into the memory. One end of the MPs queue connects to the output of a process. This process will put information into the pipeline. The other end of the MPs queue connects to the input of a process. This process extracts the information that is put into the MPs queue. A buffer zone does not need to be large. It is designed as a circular data structure so that pipelines can be recycled. If there is no information in the pipeline, the process read from the pipeline will wait until the process at the other end is put in the information. When the pipeline is filled with information, the process that tries to put the information will wait until the process at the other end retrieves the information. When both processes are terminated, the MPs queue automatically disappears.

The following is a simple example. first look at the common commands in two linux systems.

Grep

Function Description: Find the matching strings in the file.

Syntax: grep [-abcEFGhHilLnqrsvVwxy] [-A <display columns>] [-B <display columns>] [-C <display columns>] [-d <action>] [-e <template style>] [-f <Template File>] [-- help] [template style] [file or directory...]

Note: The grep command is used to find a file whose content contains the specified template style. If the content of a file conforms to the specified template style, the default grep command displays the column containing the template style. If no file name is specified or the given file name is "-", the grep command reads data from the standard input device.


Ls

Function Description: Lists All subdirectories and files in the target directory.

Syntax: ls [Option] [directory name]


You can use "|" to create an MPS queue and link the two processes together.

Terminal Operation


The files or folders with in the file name under the directory are displayed as follows:



In the linux kernel, the actual operations are as follows:

1. Call the pipe () system call. Assume that pipe () returns the file descriptor 3 (the read channel of the pipeline) and 4 (The write channel of the pipeline ).

2. Two fork () system calls.

3. Call close () twice to release the file descriptor 3 and 4.


MPs queue

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>int pipe_default[2];int main(){pid_t pid;char buffer[32];memset(buffer, 0, 32);if(pipe(pipe_default) < 0){printf("Faild to create pipe.\n");return 0;}//Child processif(0 == (pid =fork())){close(pipe_default[1]);if(read(pipe_default[0], buffer, 32) > 0){printf("Receive data from server, %s!\n", buffer);}close(pipe_default[0]);}else     //Parent process{close(pipe_default[0]);if(-1 != write(pipe_default[1], "Fuck", strlen("Fuck"))){printf("Send data to client,Fuck!\n");}close(pipe_default[1]);waitpid(pid,NULL,0);}return 1;}




It mainly explains several related functions.

Int pipe (int filedes [2]);
Filedes [0] is used to read data. When reading data, you must close the writing end, that is, close (filedes [1]);
Filedes [1] is used to write data. When writing data, you must close the reader, that is, close (filedes [0]).


Void * memset (void * s, char ch, size_t n );
Replace the first n Bytes (typedef unsigned int size_t) in s with ch and return s.


Pid_t waitpid (pid_t pid, int * status, int options );

Temporarily stop the execution of the current process until a signal arrives or the sub-process ends.


Read and write send data to the pipeline respectively.


Semaphores

When creating a semaphore, you must set an initial value to indicate that several tasks can access the shared resources protected by the semaphore at the same time. When the initial value is 1, it becomes Mutex ), that is, only one task can access the shared resources protected by semaphores.

To access shared resources, a task must first obtain a semaphore. The semaphore acquisition operation will reduce the semaphore value by 1. If the current semaphore value is negative, it indicates that the semaphore cannot be obtained, the task must be suspended in the wait queue of the semaphore to wait for the semaphore to be available. If the current semaphore value is not negative, it means that the semaphore can be obtained, so that the shared resources protected by the semaphore can be accessed immediately.

After a task accesses a shared resource protected by semaphores, it must release the semaphores. By adding the semaphores value to 1, if the semaphores value is not a positive number, it indicates that a task is waiting for the current semaphore, so it also wakes up all tasks waiting for the semaphore.

The specific definitions of PV atomic operations are as follows: (a good understanding is very important)
● P operation: if there are available resources (signal value> 0), the process in which the operation is located occupies one resource (the signal value is reduced by 1 to enter the critical Code ); if there are no available resources (signal value = 0), the process in which the operation is located is blocked until the system allocates resources to the process (entering the waiting queue, wait until the resource is the turn of the process ).
● V Operation: if a process is waiting for resources in the wait queue of the semaphore, a blocked process is awakened. If no process is waiting for it, a resource is released (that is, the signal value is increased by 1 ).

An example of implementing a PV operation.

#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>#define DELAY_TIME 5union semun{int val;struct semid_ds *buf;unsigned short *array;};int initsem(int sem_id, int init_value);int del_sem(int sem_id);int sem_p(int sem_id);int sem_v(int sem_id);int main(void){pid_t result;int sem_id;sem_id = semget(ftok(".",'a'),1,0666|IPC_CREAT);init_sem(sem_id, 0);result = fork();if(result == -1){perror("fork error!\n");}else if(result == 0){printf("Child process at id:%d, I run first.\n",getpid());sleep(DELAY_TIME);sem_v(sem_id);}else{sem_p(sem_id);printf("Parent process at id:%d\n",getpid());sem_v(sem_id);del_sem(sem_id);}return 0;}int init_sem(int sem_id, int init_value){union semun sem_union;sem_union.val = init_value;if(semctl(sem_id, 0, SETVAL, sem_union) == 1){perror("Init semaphore!");return -1;}return 0;}int del_sem(int sem_id){union semun sem_union;if(semctl(sem_id, 0, IPC_RMID, sem_union) == 1){perror("Delete semaphore!");return -1;}}int sem_p(int sem_id){struct sembuf sem_b;sem_b.sem_num = 0;sem_b.sem_op = -1;sem_b.sem_flg = SEM_UNDO;if(semop(sem_id, &sem_b, 1) == -1){perror("P operation.");return -1;}return 0;}int sem_v(int sem_id){struct sembuf sem_b;sem_b.sem_num = 0;sem_b.sem_op = 1;sem_b.sem_flg = SEM_UNDO;if(semop(sem_id, &sem_b, 1) == -1){perror("P operation.");return -1;}return 0;}



In the program, the semaphore is used to ensure that each sub-process runs before the parent process.



Reference

Linux inter-process communication (6) --- semget (), semctl (), semop () and Basic Experiment-http://blog.csdn.net/mybelief321/article/details/9086151

Linux environment inter-process communication (I)-http://www.ibm.com/developerworks/cn/linux/l-ipc/part1/

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.