Interprocess communication shared memory + semaphores

Shared memory is the fastest form of IPC ,, Once such a memory-mapped into the process address space, these data will no longer be involved in kernel space.

ipcs -m view shared memory

Several shared memory function

0 Request a shared memory id

key_t key = ftok(“PathName” , Project_id);

1 Create a shared memory

int shmget (key_t key, size_t size
, int shmflg); parameters:
Key: id ftok obtained shared memory
size: the size of the shared memory

shmflg: similar to the mode when the file is created,
the return value: the successful return of shared memory code shmid, failed to return -1

shmflag:
IPC_CREAT, does not exist is created, there is a return to handle, shmid

IPC_EXCL | IPC_CREAT:创建,存在就出错返回

2 shmat () the shared memory segment to the process address space

void* shmat(int shmid,const void*shmaddr, int shmflg)

shmid: shared memory code,

shmaddr: the specified address (typically an empty set, allocated by OS) connection, i.e. a return value of shmat

shmflg: two possible values

SHM_RND 和SHM_RDONLY 
SHM_RND为低边界地址的倍数(2的乘方)
公式:SHM_ADDR -=  SHMADDR%SHMLBA

shmaddr is NULL, the kernel chooses an address

Returns: successful returns a pointer to the shared memory handle,
failed to return -1

3 shmdt: shared memory with the current process from
(out = deleted!)

shmdt int (const void * by shmaddr);
by shmaddr shared memory address, i.e. shmat return value
Return value: Success: 0 Failed -1

4 shmctl control of the shared memory

int shmctl (int shmid, int cmd, struct shmid_ds *buf)

the shmid (shared memory operation handle)

cmd: actions to be taken

-Stat command ipcs
ipcs -set

System V shared memory

Step shared memory:
a create / open ftok shared memory object ( "present path" arbitrary integer);
EG: key_t ftok ( ".", 0x02) can be written as a function just the same parameters, must be shared memory

ID value must specify a communication system establishing IPC (message queues, semaphores, and shared memory). Typically, the value obtained by ftok id function.
Return Value that only eight valid 0-255

2 attached to a shared memory object (shmat-> attach) and the usage is very similar to malloc
eg: void * shmat (shmid, NULL ( decided by the system virtual address, 0), when a strong need to manually turn,

3 uses shared memory
to write, read
shared memory and different pipes, pipe is a visit to the queues, shared memory is the common memory,

message queue

A band type of queues, each queue in accordance with the specified type

The IPC (shared memory semaphore message queues)
generalized message queue is a queue, each queue element comes with a type, out of the team in FIFO order

Message Queuing server cluster is actually a large message queue, he contains a number of service parts, service parts regardless of the business, there are a lot of client programs, carried out a particular team through a network of
message queue provided from one process to another a method of sending data to
IPC resources must be removed, it would not automatically cleaned up. Unless manually restart, the System V IPC life cycle with the kernel

System V semaphores

Role: process synchronization and mutual exclusion

In essence, a queue counter + PCB

Counter is a count of resources, + 1 or -1;
values 0 and 1 only

principle:

Before accessing critical resource, the semaphore counter value look is -1 or 0 (pre minus 1, does not really reduce)

If 0 represents the critical resources are available when accessing critical resources -1;

When you exit, and then +1 critical resource,

When access to critical resources such a process, other processes can only wait, and wait for the process in the semaphore wait queue PCB, a block waiting

So that to achieve inter-process mutex,

Synchronization means that when
the former non-disruptive operation can achieve their goals, rather than a moment before reaching the goal.

Synchronization process, the counter will no longer be restricted to 0 or 1, but can take any value. The counter is initialized to the number of resources.

When accessing resources (P operation), the counter will be pre-1 operation,

If greater than or equal to 0, the critical access resources (i.e., PCB tell the queue can access resources)

Mutual exclusion : Some operating process memory when another process can not be allowed to use the same memory at the same time, so the competition between the various processes that use memory resources, this is the mutual exclusion

Critical Resource (mutually exclusive resources): system resources can only be used by a process known as the critical resources.

The critical area : the system involves the use of critical resource program called the critical zone
IPC resources must be removed, it would not automatically cleaned up. Unless manually restart, the System V IPC life cycle with the kernel

signal:

Is a way to signal asynchronous event notifications between processes, are soft interrupt. Here Insert Picture Description
There are 62 kinds of signals, no kind of signal has its own serial number and a name of a macro defined
role: the process is carried out there is a case to inform, inform the current system (not necessarily wrong) state,

Signal processing:
1 Ignore
default signal processing operations performed 2
3 users provides a signal processing function, the kernel signals captured, simulated user to perform this function, referred to as signal capture (catch).

Signal generation:

1 keyboard
eg: ctrl + c -> SIGINT No. 2
Ctrl + Z -> the SIGTSTP screen lock 20 is
Ctrl + S unlock
ctrl + | 15 signal termination signal

Hardware ** 2 **
EG: a signal (signal 11, burst error) generated MMU MMU is responsible for translating a virtual address into a physical address, is responsible for mapping between logical addresses and physical addresses

		若非法,MMU硬件设备给OS发送这个错误情况,然后**OS给程序发送11号信号**(MMU负责管理内存单元,)
		eg: 解引用空指针
        eg :  CPU 发出的8号信号 浮点数异常
        	    (除0运算)

3 software

1 assertion assert ()

	   类似MMU将虚拟翻译为物理
	   进程遇到abort  ()函数而异常终止

abort the process he would hang himself (hanging from the southeast branch)

void abort (void) abort function always successful, so there is no return value

pipe read end is not closed appear SIGPIPE (pipe rupture), this guy does not have any error notice will explain the failure error.

2 alarm function (set off time)
int Alarm (SECOND unsigned int)
returns the number of seconds remaining time is zero or the current setting

该函数的执行结果是终止当前进程

7
capture signal using the signal () function man to look at signal function Here Insert Picture Description
, we found that two parameters, a signal number, a function pointer, we can all achieve their own Oh! Runtime, this time the kill -9 command any natural and effective

When the second argument is SIG_IGN, ignored the signal, not captureHere Insert Picture Description

3 calling function generator:

actually called bottom kill function to kill the
kill (number, pid) sends a signal to the specified process

raise () signal to yourself

abort () process to kill himself

Signal blocking:

Sometimes inconvenient to immediately signal to be processed, and then wait for the opportunity to be processed

Signal pending signal set 1: from production to delivery of:
2 sets the blocking signals: identification signal that can not be processed immediately, set to block the signal through a number of functions.
3 set of signal processing functions: as an internal array of function pointers ----- ------------- internal memory array for signal processing function
we use to store the bit map signal 64 is a unsigned integer 0-63

Questions : 1 the same time received a large number of one signal (signal only discuss the No. 1-31) will be a problem
2 a function at the time of the execution flow multiple execution may be a problem, (eg: perform a half, triggering another a function, then ran to execute another, so the problem will appear)

For re-entry is a function of:

Then, if a function is not executed in multiple streams, we call this function reentrant functions otherwise known as non-reentrant functions
Note that only a recursive execution flow
**
how to determine non-reentrant: ** 1 function calls global variable / static variable, non-reentrant
2 malloc (in essence, is called a global variable)
3 called non-reentrant function can not reentrant
O library, to achieve 4 calls the standard I / standard I / O library the basic rules are written in a non-reentrant, the basic global data structures are

volatile: C language keyword **, which is the pit, not easy to find **, code optimization may be a BUG,

volatile告诉编译器不要将变量优化到寄存器中,每次都去内存中读.

Often used in multi-thread, multi-thread, often wrong (such as lazy mode).

waitpid

	  如果在调用 waitpid()时子进程已经结束,则 waitpid()会立即

Ending state value is returned child process. End state child process value is returned by the parameter status,

The child process will be returned along with the identification code. If you do not care about the end of the state value,

Status parameter can be set to NULL. Argument pid process ID for the child want to wait,

Other numerical significance as follows:

pid <-1 wait for any child process group identification code is the absolute process pid.

pid = -1 wait for any child process equivalent to wait ().

pid = 0 the process waits for the current group identifier with the same process any child processes.

pid> 0 wait for any child process ID for the child process pid.

Parameter options to provide some additional options to control waitpid, parameter option can be zero or can use "|" operator to connect them to use, such as:

ret=waitpid(-1,NULL,WNOHANG | WUNTRACED);

If we do not want to use them, the options can be set to 0, such as:

ret=waitpid(-1,NULL,0);

WNOHANG If pid specified child process is not completed, the waitpid () function returns 0, not be waiting. If the ending, ID of the child process is returned.

WUNTRACED if the child enters the suspend state, immediately returned, but the end state of the child process is not to be ignored. WIFSTOPPED (status) macro determines whether the return value corresponds with a suspended child process.

After the end of the state of the child process returns stored in status, under a few macros can determine the end of the case:

WIFEXITED (status) If a normal end status if the child process is returned TRUE; this case executable WEXITSTATUS (status), to take the child process is passed to a low exit or _eixt 8.

WEXITSTATUS (status) to obtain the child process exit () returns the end code, usually first with WIFEXITED to determine whether the normal end to use this macro.

WIFSIGNALED (status) If the state is returned to the child process ends abnormally, True; this case executable WTERMSIG (status), the end of the number of the signal to take the child process.

WTERMSIG (status) acquires a signal code which the child aborted due to a signal, and will normally be determined by WIFSIGNALED after use this macro.

WIFSTOPPED (status) If the current state is the suspend child returns TRUE; this case executable WSTOPSIG (status), the process taking that the signal-numbered sub-suspended.

WSTOPSIG (status) code that caused the child process to obtain a signal pause, the general will be determined after the first use WIFSTOPPED use this macro.

If successful child process ID (PID) is returned, if there is an error is returned

Return value of -1. The reason for the failure is stored in errno.

Published 90 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44030580/article/details/103612619