Unix_c_07.txt
================
Seventh Lesson Process Communication
================
First, the basic concept
------------
1. What is interprocess communication
~~~~~~~~~~~~~~~~~
interprocess communication (interprocess communication, IPC) refers to two,
or process of data exchange between multiple processes.
2. Inter-process communication classification
~~~~~~~~~~~~~~~~~
1) Simple interprocess communication: command line parameters, environment variables, signals, files.
2) Traditional interprocess communication: Pipelines (fifo/pipe).
3) XSI interprocess communication: Shared memory, Message queue, semaphore.
4) Network interprocess communication: Socket.
Ii. traditional inter-process communication-pipelines
--------------------------
1. Pipelines are the oldest form of interprocess communication between UNIX systems.
2. Historically, pipelines usually refer to half-duplex pipes,
Only one-way flow of data is allowed. Most modern systems offer full-duplex piping,
Data can flow in two directions along a pipe.
3. Well-known pipeline (FIFO): Pipeline communication based on a well-known file (pipe file).
1) Command form
# Mkfifo FIFO
# echo Hello > FIFO # cat FIFO
2) programming model
------+----------+------------+----------+------
Steps | Process A | function | Process B | Steps
------+----------+------------+----------+------
1 | Creating Pipelines | Mkfifo | ---- |
2 | Open Pipe | Open | Open Pipe | 1
3 | Read/write Pipeline | Read/write | Read/write Pipeline | 2
4 | Close Pipe | Close | Close Pipe | 3
5 | Delete Pipeline | unlink | ---- |
------+----------+------------+----------+------
Example: WFIFO.C, RFIFO.C
Diagram: Fifo.bmp
1th page Unix_c_07.txt
4. Nameless pipe (pipe): Applies to communication between parent and child processes.
#include <unistd.h>
int pipe (int pipefd[2]);
1) successfully returned 0, failed to return-1.
2) return two file descriptors via output parameter pipefd,
Where Pipefd[0] is used for reading, pipefd[1] for writing.
3) General usage
A. Call this function to create a pipe file in the kernel, and through its output parameters,
Obtain two file descriptors for reading and writing respectively;
B. Call the fork function to create the child process;
C. The process of writing data closes the read end (Pipefd[0]),
The process of reading the data closes the write end (pipefd[1]);
D. Transmission of data;
E. Parent-child processes close their own file descriptors separately.
Diagram: Pipe.bmp
Example: pipe.c
Iii. XSI inter-process communication
-----------------
1. IPC logo
~~~~~~~~~~
The kernel maintains an IPC object in the form of a struct for each interprocess communication.
The object can be referenced by an IPC identifier of a non-negative integer.
Unlike file descriptors, the IPC logo will continue to add 1 when used,
When the maximum value is reached, turn to 0.
2. IPC Key value
~~~~~~~~~~
The IPC identifier is the internal name of the IPC object.
If multiple processes need to meet on the same IPC object,
The object must be referenced by the key value as its external name.
1) Whenever you create an IPC object, you must specify a key value.
2) The data type of the key value is defined as key_t in the Sys/types.h header file,
The original type is the long integer type.
3. Three ways to rendezvous client processes and server processes on IPC objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2nd Page Unix_c_07.txt
1) The server process creates a new IPC object with Ipc_private as the key value.
and store the identity of the IPC object somewhere, such as a file,
To facilitate read by the client process.
2) in a common header file,
Defines a key value that is recognized by both the client process and the server process.
The server process creates an IPC object with this key value.
The client process obtains the IPC object with this key value.
3) client processes and server processes,
Prior agreement good one path name and a project ID (0-255),
The two pass the Ftok function,
Converts the path name and project ID to a consistent key value.
#include <sys/types.h>
#include <sys/ipc.h>
key_t Ftok (const char* pathname, int proj_id);
Pathname-A path name for a real file or directory that exists.
PROJ_ID-the project ID, which is valid only for low 8 bits, has a value of [0,255].
The key value returned successfully, and the failure returns-1.
Note: The path represented by the pathname parameter is working,
Rather than pathname the string itself.
So assuming the current directory is/home/soft01/uc/day07, then
Ftok (".", 100);
And
Ftok ("/home/soft01/uc/day07", 100);
The return value is exactly the same.
4. Creation of IPC objects
~~~~~~~~~~~~~~~~
1) If you create an IPC object with Ipc_private as the key value,
is always created successfully.
2) If the specified key value is not combined with any IPC object within the system range,
And the CREATE flag contains the Ipc_creat bit, the creation succeeds.
3) If the specified key value has been combined with an IPC object within the system scope,
And the CREATE flag contains the ipc_creat and ipc_excl bits, the creation fails.
5. Destruction/control of IPC objects
~~~~~~~~~~~~~~~~~~~~~
Ipc_stat-Get IPC Object properties
Ipc_set-Setting IPC Object properties
Ipc_rmid-Delete IPC objects
Iv. Shared Memory
------------
1. Basic Features
3rd page Unix_c_07.txt
~~~~~~~~~~~
1) Two or more processes,
Share the same block of memory area that is maintained by the system kernel,
Its address space is usually mapped between the heap and the stack.
Diagram: Shm.bmp
2) No need to copy information, the fastest kind of IPC mechanism.
3) You need to consider the issue of synchronous access.
4) kernel for each shared memory,
Maintains a shared memory object in the form of a shmid_ds struct.
2. Common functions
~~~~~~~~~~~
#include <sys/shm.h>
1) Create/Get shared memory
int Shmget (key_t key, size_t size, int shmflg);
A. The function creates shared memory with the key parameter
Or get the existing shared memory.
B. The size parameter is the number of bytes in shared memory,
It is recommended to take an integer multiple of the memory page bytes (4096).
If you want to create shared memory, you must specify the size parameter.
The size parameter is 0 if only to get the existing shared memory.
C. SHMFLG Value:
0-Gets, does not exist or fails.
Ipc_creat-Creates, does not exist, is created,
Already existing is acquired, unless ...
IPC_EXCL-exclusion, which already exists that fails.
D. Successful return of shared memory identity, failed return-1.
2) Load Shared memory
void* shmat (int shmid, const void* SHMADDR,
int SHMFLG);
A. The shared memory identified by the Shmid parameter,
Map to the address space of the calling process.
B. The mapping address can be specified by the SHMADDR parameter.
You can also set the parameter to NULL, which is automatically selected by the system.
C. SHMFLG Value:
4th page Unix_c_07.txt
0-Use shared memory in read-write mode.
Shm_rdonly-Use shared memory in read-only mode.
Shm_rnd-works only when the SHMADDR parameter is not NULL.
Represents an integer multiple of the memory page to which the parameter is taken.
As the mapping address.
D. Successful return of the mapped address, failed to return-1.
E. The kernel adds 1 to the load count of the shared memory.
3) Offload shared memory
int SHMDT (const void* SHMADDR);
A. From the address space of the calling process,
Cancels the shared memory-mapped area that is pointed to by the SHMADDR parameter.
B. Successful return 0, failure return-1.
C. The kernel will reduce the load count of this shared memory by 1.
4) Destroy/control shared memory
int shmctl (int shmid, int cmd, struct shmid_ds* buf);
struct Shmid_ds {
struct Ipc_perm shm_perm; Owners and their permissions
size_t Shm_segsz; Size (in bytes)
time_t Shm_atime; Last Load time
time_t Shm_dtime; Last Unload time
time_t Shm_ctime; Last change of time
pid_t Shm_cpid; Creating a process PID
pid_t Shm_lpid; Last load/unload process PID
shmatt_t Shm_nattch; Current Load Count
...
};
struct Ipc_perm {
key_t __key; Key value
uid_t uid; Valid Master ID
gid_t GID; Valid Group ID
uid_t cuid; Valid Creator ID
gid_t Cgid; Create group IDs effectively
unsigned short mode; Permission Word
unsigned short __seq; Serial number
};
A. CMD value:
Ipc_stat-Gets the properties of the shared memory, output through the BUF parameter.
Ipc_set-Sets the properties of the shared memory, entered by the BUF parameter,
Only the following three properties can be set:
5th page Unix_c_07.txt
Shmid_ds::shm_perm.uid
Shmid_ds::shm_perm.gid
Shmid_ds::shm_perm.mode
Ipc_rmid-Tags delete shared memory.
Instead of actually deleting the shared memory, just make a delete tag,
It is forbidden to continue loading, but the load is still retained.
Only if the shared memory load count is 0 o'clock,
is actually deleted.
B. Successful return 0, failure return-1.
3. Programming model
~~~~~~~~~~~
------+--------------+--------+--------------+------
Steps | Process A | function | Process B | Steps
------+--------------+--------+--------------+------
1 | Create Shared Memory | Shmget | Get Shared Memory | 1
2 | Load Shared Memory | Shmat | Load Shared Memory | 2
3 | Using Shared Memory | ... | Using Shared Memory | 3
4 | Offload Shared Memory | SHMDT | Offload Shared Memory | 4
5 | Destroying Shared Memory | Shmctl | ---- |
------+--------------+--------+--------------+------
Example: WSHM.C, RSHM.C
V. Message Queuing
------------
1. Basic Features
~~~~~~~~~~~
1) Message Queuing is a system kernel that is responsible for storing and managing
and identifies the referenced data link list through Message Queuing.
2) A new message queue can be created through the Msgget function,
Or get an existing message queue.
Appends a message to the back end of a message queue through the MSGSND function.
Extracts a message from the front end of a message queue through the MSGRCV function.
3) Each message unit in the message queue, in addition to the message data,
It also contains the message type and data length.
4) The kernel is for each message queue,
Maintains a Message Queuing object in the form of a msqid_ds struct.
2. Common functions
~~~~~~~~~~~
#include <sys/msg.h>
1) Create/Get Message queue
int Msgget (key_t key, int msgflg);
6th page Unix_c_07.txt
A. The function creates a message queue with the key parameter
Or get the existing message queue.
B. MSGFLG Value:
0-Gets, does not exist or fails.
Ipc_creat-Creates, does not exist, is created,
Already existing is acquired, unless ...
IPC_EXCL-exclusion, which already exists that fails.
C. Successful return message queue identity, failed return-1.
2) Send message to Message queue
int msgsnd (int msqid, const void* MSGP,
size_t msgsz, int msgflg);
A. The MSGP parameter points to a block of memory that contains the message type and message data.
The first 4 bytes of the memory block must be an integer greater than 0,
Represents the message type followed by the message data.
The byte length of the message data is represented by the MSGSZ parameter.
+---------------+-----------------+
MSGP | Message type (>0) | Message Data |
+---------------+-----------------+
|<-----4----->|<----MSGSZ---->|
Note: The MSGSZ parameter does not contain the number of bytes of the message type (4).
B. If the message queue buffer in the kernel has enough free space,
This function will copy the message into the buffer and return 0 immediately.
Indicates a successful send, otherwise this function will block,
Until the message queue buffer in the kernel has enough free space
(such as a message being received).
C. If the MSGFLG parameter contains ipc_nowait bits,
When there is not enough free space in the message queue buffers in the kernel,
This function does not block, but returns -1,errno to Eagain.
D. Successful return 0, failure return-1.
3) receive messages from Message Queuing
ssize_t MSGRCV (int msqid, void* msgp, size_t Msgsz,
Long Msgtyp, int msgflg);
A. The MSGP parameter points to a containing message type (4 bytes),
And the memory blocks of the message data,
Where the byte size of the message data buffer is represented by the MSGSZ parameter.
B. If the received message data bytes are greater than the MSGSZ parameter,
That is, the message is too long, and the MSGFLG parameter contains the MSG_NOERROR bit,
The message is intercepted Msgsz bytes are returned and the remainder is discarded.
7th page Unix_c_07.txt
C. If the MSGFLG parameter does not contain a msg_noerror bit, the message is too long,
No processing is done for the message, and the -1,errno is returned directly to E2big.
D. The Msgtyp parameter indicates what type of message is expected to be received:
=0-Returns the first message in the message queue.
>0-If the MSGFLG parameter does not contain msg_except bits,
Returns a message with the first type of Msgtyp in the message queue;
If the MSGFLG parameter contains a msg_except bit,
Returns a message with the first type in the message queue that is not Msgtyp.
<0-Returns a message in the message queue with a type less than or equal to the absolute value of Msgtyp.
If there are more than one, the least type is taken.
+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 3 | 4 | 2 | 1 | 3 | 2 | 4 | 3 | 3 |
-Rear +--+--+--+--+--+--+--+--+--+ Front
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+
^ ^ ^ ^
4 3 2 1
MSGRCV (...,......., 3,...);
E. If there are messages in the message queue that can be received,
This function moves the message out of the message queue and returns 0 immediately.
Indicates that the receive succeeds, otherwise this function will block,
Until a message is received in the message queue.
F. If the MSGFLG parameter contains ipc_nowait bits,
This function does not block when there are no messages to receive in the message queue.
Instead, return -1,errno to Enomsg.
G. The number of bytes that successfully returned the received message data, failure returns-1.
4) destroying/controlling Message Queuing
int msgctl (int msqid, int cmd, struct msqid_ds* buf);
struct Msqid_ds {
struct Ipc_perm msg_perm; Permission information
time_t Msg_stime; Subsequent send time
time_t Msg_rtime; Last Received Time
time_t Msg_ctime; Last change of time
unsigned long __msg_cbytes; Number of bytes in Message Queuing
Msgqnum_t Msg_qnum; Number of messages in Message Queuing
Msglen_t msg_qbytes; Maximum number of bytes that Message Queuing can hold
pid_t Msg_lspid; Last send process PID
pid_t Msg_lrpid; Last receive process PID
};
struct Ipc_perm {
key_t __key; Key value
uid_t uid; Valid Master ID
gid_t GID; Valid Group ID
8th Page Unix_c_07.txt
uid_t cuid; Valid Creator ID
gid_t Cgid; Create group IDs effectively
unsigned short mode; Permission Word
unsigned short __seq; Serial number
};
A. CMD value:
Ipc_stat-Gets the properties of the message queue, which is output through the BUF parameter.
Ipc_set-Sets the properties of the message queue, entered by the BUF parameter,
Only the following four properties can be set:
Msqid_ds::msg_perm.uid
Msqid_ds::msg_perm.gid
Msqid_ds::msg_perm.mode
Msqid_ds::msg_qbytes
Ipc_rmid-Deletes Message Queuing immediately.
At this point all are blocked on the message queue,
Msgsnd and MSGRCV function calls,
Will immediately return to failure, errno to EIDRM.
B. Successful return 0, failure return-1.
3. Programming model
~~~~~~~~~~~
------+--------------+---------------+--------------+------
Steps | Process A | function | Process B | Steps
------+--------------+---------------+--------------+------
1 | Create Message Queue | Msgget | Get Message Queuing | 1
2 | Send Receive Message | MSGSND/MSGRCV | Send Receive Message | 2
3 | Destroying message Queues | Msgctl | ---- |
------+--------------+---------------+--------------+------
Example: WMSQ.C, RMSQ.C
Exercise: A local bank based on Message Queuing.
Code: bank/
Six, the signal volume
----------
1. Basic Features
~~~~~~~~~~~
1) counter, which restricts access to limited shared resources by multiple processes.
2) Multiple processes get the operating mode of limited shared resources
A. Test the semaphore that controls the resource;
B. If the semaphore is greater than 0, the process can use the resource,
To indicate that this process has obtained this resource, the semaphore needs to be reduced by 1;
9th Page Unix_c_07.txt
C. If the semaphore equals 0, the process sleeps and waits for the resource,
Until the semaphore is greater than 0, the process is woken up, performing step A;
D. When a process no longer uses the resource, the semaphore increases by 1,
Other processes that are sleeping waiting for the resource will be awakened.
2. Common functions
~~~~~~~~~~~
#include <sys/sem.h>
1) Create/Get Semaphore
int Semget (key_t key, int nsems, int semflg);
A. The function creates a semaphore set with the key parameter as the value
(the Nsems parameter represents the number of semaphores in the collection),
Or get an existing set of semaphores (Nsems take 0).
B. SEMFLG Value:
0-Gets, does not exist or fails.
Ipc_creat-Creates, does not exist, is created,
Already existing is acquired, unless ...
IPC_EXCL-exclusion, which already exists that fails.
C. Successful return semaphore set identity, failure return-1.
2) Operating Signal volume
int semop (int semid, struct sembuf* sops,
unsigned nsops);
struct SEMBUF {
unsigned short sem_num; Signal volume subscript
Short Sem_op; Number of operands
Short SEM_FLG; Action Tag
};
A. In the set of semaphores identified by the function for the Semid parameter,
With nsops elements pointed to by the SOPs parameter,
Each element in the struct array, in turn, do the following:
A) If SEM_OP is greater than 0,
It is added to the count value of the Sem_num semaphore,
To express the release of resources;
b) If Sem_op is less than 0,
Subtract the absolute value from the count of the number of Sem_num semaphores,
To represent the acquisition of resources;
c) If the count value of the Sem_num semaphore is not reduced (the semaphore cannot be negative),
This function blocks until the semaphore is reduced enough,
10th page Unix_c_07.txt
To indicate the waiting for the resources;
D) If SEM_FLG contains ipc_nowait bits,
When the count value of the Sem_num semaphore is not reduced enough,
This function does not block, but returns -1,errno to Eagain,
So that other processing can be done while waiting for the resources;
e) If Sem_op equals 0,
The Sem_num semaphore is not returned until the count of the number is 0 o'clock.
Unless SEM_FLG contains ipc_nowait bits.
B. Successful return 0, failure return-1.
3) Destruction/control signal volume
int semctl (int semid, int semnum, int cmd);
int semctl (int semid, int semnum, int cmd,
Union Semun Arg);
Union Semun {
int Val; Value for Setval
struct semid_ds* buf; Buffer for Ipc_stat, Ipc_set
unsigned short* array; Array for GETALL, SETALL
struct seminfo* __buf; Buffer for Ipc_info
};
struct Semid_ds {
struct Ipc_perm sem_perm; Ownership and Permissions
time_t Sem_otime; Last Semop time
time_t Sem_ctime; Last Change time
unsigned short sem_nsems; No. of semaphores in Set
};
struct Ipc_perm {
key_t __key; Key value
uid_t uid; Valid Master ID
gid_t GID; Valid Group ID
uid_t cuid; Valid Creator ID
gid_t Cgid; Create group IDs effectively
unsigned short mode; Permission Word
unsigned short __seq; Serial number
};
A. CMD value:
Ipc_stat-Gets the properties of the semaphore collection, through the ARG.BUF output.
Ipc_set-Sets the properties of the semaphore collection, via Arg.buf input,
Only the following four properties can be set:
Semid_ds::sem_perm.uid
Semid_ds::sem_perm.gid
Semid_ds::sem_perm.mode
Ipc_rmid-Deletes the semaphore collection immediately.
At this point all blocks are in the set of the semaphore,
11th Page Unix_c_07.txt
The SEMOP function call will immediately return a failure,
errno for EIDRM.
GETALL-Gets the count value of each semaphore in the semaphore collection,
Output via Arg.array.
SETALL-Sets the count value of each semaphore in the semaphore set,
Input via Arg.array.
Getval-Gets the amount of semaphore in the collection,
The count value of the Semnum semaphore,
Output by return value.
Setval-Sets the semaphore set,
The count value of the Semnum semaphore,
Input via Arg.val.
Note: Only the operation for a specific semaphore in the semaphore set
The Semnum parameter is used. For the entire semaphore set operation,
The Semnum parameter is ignored.
B. The successful return value varies by cmd, and the failure returns-1.
3. Programming model
~~~~~~~~~~~
------+------------+--------+------------+------
Steps | Process A | function | Process B | Steps
------+------------+--------+------------+------
1 | Create Semaphore | Semget | Get the Semaphore | 1
2 | Initial Signal Volume | Semctl | ---- |
3 | Add and Subtract semaphores | Semop | Add and Subtract semaphores | 2
4 | Destroy Signal Volume | Semctl | ---- |
------+------------+--------+------------+------
Example: CSEM.C, GSEM.C
Vii. IPC Command
-----------
1. Display
~~~~~~~
IPCS-M-Show Shared memory (M:memory)
IPCS-Q-Display Message Queuing (q:queue)
Ipcs-s-Display signal volume (S:semphore)
IPCS-A-Show All IPC objects (A:all)
2. Delete
~~~~~~~
Ipcrm-m ID-Delete shared memory
Ipcrm-q ID-Delete Message Queuing
Ipcrm-s ID-delete semaphore
12th Page
Seventh Lesson Process Communication