Linux system programming (4)

Source: Internet
Author: User
Tags message queue semaphore

An IPC object----Message Queuing

IPC Object Commands

(1) View IPC objects in the system
IPCS-A display of all IPC objects
Ipcs-s/-q/-m

(2) Remove IPC objects from the system
Ipcrm-q/-s/-m ID


1. Get the key value

The first type:
key_t Ftok (const char *pathname, int proj_id);
Parameters:
@pathname a file path that already exists
@proj_id gets the low 8bit of this integer
return value:
Successful return key value, failure return-1


The second type:
Specify the key value as ipc_private when the IPC object communicates with the affinity process


2. Creating IPC objects
int Msgget (key_t key, int msgflg);
Parameters:
@key Ipc_private or Ftok
@msgflg Ipc_creat | 0666 or Ipc_creat | Ipc_excl | 0666 (determine if the IPC object exists)
return value:
Successful return ID, failure return-1

Attention:
If the IPC object corresponding to the key value does not exist, then create, if present, return the ID of the IPC object directly

3. Send a message
int msgsnd (int msqid, const void *MSGP, size_t msgsz, int msgflg);
@msqid Message Queue ID
@msgp the address where the message to be sent is stored
@msgsz the size of the message body
@msgflg 0: Blocked way to send ipc_nowait: Non-blocking method invocation
return value:
Successful return 0, failure return-1

message struct Definition:

typedef struct{
Long Msg_type; The message type must be in the first position,
Char mtxt[1024];
...
}msg_t;

Body size: sizeof (msg_t)-sizeof (long)

4. Receiving Messages
ssize_t MSGRCV (int msqid, void *msgp, size_t msgsz, Long msgtyp,int MSGFLG);
Parameters:
@msqid Message Queue ID
@msgp to store received messages
@msgsz Body Size
@msgtyp message type, 0: Always extracts the first message from a message queue
@msgflg 0: Blocked way to receive ipc_nowait: Non-blocking method invocation
return value:
Successful return receive message body size, failed return-1

4. Delete Message Queuing
int msgctl (int msqid, int cmd, struct msqid_ds *buf);
Parameters:
@msgqid Message Queuing
@cmd ipc_rmid (Delete Message Queuing) Ipc_set (set property information for Message Queuing) ipc_stat (Get Message Queuing property information)
@buf Storing Message Queuing properties
return value:
Successful return 0, failure return-1

Practice:
Implementing two-process communication

Two shared memory: a piece of memory reserved by the kernel space for interprocess communication

(1) int shmget (key_t key, size_t size, int shmflg);

Function: Gets the ID of the shared memory segment

Parameters:
@key ipc_private or Ftok ()
@size the requested shared memory segment size [multiples of 4k]
@shmflg Ipc_creat | 0666 or Ipc_creat | Ipc_excl

return value:
Successful return ID, failure return-1

(2) void *shmat (int shmid, const void *shmaddr, int shmflg);
Function: Map shared memory to user space
Parameters:
@shmid Shared memory Segment ID
@shmaddr NULL: System Auto-complete mapping
@shmflg shm_rdonly: Read-only 0: Read and write
return value:
Successful return of mapped address, failed return (void *)-1

Exercise: A/b communicates through shared memory

b How do you know that A has already written the data?

Flag_r flag_w
-------------------------------------------------------------------------------------
|  | Data (input from keyboard)
-------------------------------------------------------------------------------------

(3) int shmdt (const void *SHMADDR);
function: Undo Map
Parameters:
@shmaddr the address of the shared memory map

Note: When a process finishes, it maps shared memory and automatically revokes the mappings


(4) int shmctl (int shmid, int cmd, struct shmid_ds *buf);
Function: Control shared memory according to command
Parameters:
@shmid the ID of the shared memory segment
@cmd ipc_stat[Get Property],ipc_set[Set Property],ipc_rmid[Delete IPC Object]
@buf Save Properties
return value:
Successful return 0, failure return-1

----------------------------------------------------------------------------
Note: When we call Shmctl to delete the shared memory, it is not deleted immediately. Only if the shared memory map
The number of times is 0 to delete the shared memory object
-----------------------------------------------------------------------------

Three semaphore (semaphore) set

The use of anonymous semaphores in the synchronization of POSIX threads
Inter-process synchronization using IPC objects [semaphore set]

Beacon set: A set of lights, each semaphore can be used to represent a class of resources, whose value represents the number of resources

(1) Create a semaphore set
int Semget (key_t key, int nsems, int semflg);
Parameters:
@key ipc_private, Ftok ()
Number of lights in the @nsems signal set
@semflg Ipc_creat | 0666,ipc_creat | Ipc_excl
return value:
Successful return ID, failure return-1

(2) Initialize the value of the signal set signal

int semctl (int semid, int semnum, int cmd, ...);
Parameters:
ID of @semid Semaphore set
Number of @semnum lights [numbering starting from 0]
@cmd setval[Set the value of the semaphore], getval (get the value of the semaphore), ipc_rmid[delete the semaphore set]
return value:
Successful return 0, failure return-1

Think: Initialize signal 1th in the beacon set to 1?

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
(linux-specific) */
};

void Init_sem_value (int sem_id,int sem_num,int value)
{
Union Semun Sem_val;

Sem_val.val = value;

if (Semctl (Sem_id,sem_num,setval,sem_val) < 0)
{
...
}

return;
}

(3) PV operation
int semop (int semid, struct sembuf *sops, unsigned nsops);
Function: Complete PV operation
Parameters:
ID of @semid Semaphore set
@sops How to do structure body first address
Number of @nsops operation lights
return value:
Successful return 0, failure return-1

struct SEMBUF
{
unsigned short sem_num; /* Semaphore number */
Short Sem_op; /* Semaphore operation */
Short SEM_FLG; /* Operation flags */
};

Sem_op:
<1>0 wait for the semaphore to change to 0.
<2>1 Releasing resources, v operation
&LT;3&GT;-1 application resources, p operations

SEM_FLG:
0: Blocking mode
Ipc_nowait: Non-blocking method invocation
Sem_undo: At the end of the process, the resource it requested is automatically released

-----------------------------------------------------------------
void P (int sem_id,int sem_num)
{
struct SEMBUF sem;

Sem.sem_num = Sem_num;
Sem.sem_op =-1;
SEM.SEM_FLG = 0;

if (Semop (sem_id,&sem,1) < 0)
{
....
}
}

void V (int sem_id,int sem_num)
{
struct SEMBUF sem;

Sem.sem_num = Sem_num;
Sem.sem_op = 1;
SEM.SEM_FLG = 0;

if (Semop (sem_id,&sem,1) < 0)
{
....
}
}

Exercise: A, B synchronize to a shared memory operation through a semaphore set

Let the process that creates the semaphore set initialize the value of the semaphore and not initialize if the semaphore set already exists

sem_id = Semget (Key,2,ipc_creat | Ipc_excl | 0666);
if (sem_id < 0)//Semaphore set already, do not initialize semaphore value
{
sem_id = Semget (key,2,ipc_creat | 0666);

}else{
Initialize the value of the semaphore in the signal set
}


Linux system programming (4)

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.