C language programming in Linux-process communication and Message Management

Source: Internet
Author: User
C language programming in Linux-process communication and Message Management-general Linux technology-Linux programming and kernel information. For details, refer to the following section. Process Communication (IPC) in Linux)
Process Communication (IPC) in Linux)

1. POSIX unknown semaphores
2. System V semaphore
3. System V Message Queue
4. System V shared memory

--------------------------------------------------------------------------------
1. POSIX unknown semaphores if you have studied the operating system, you must be familiar with PV operations. PV operations are atomic operations. that is, the operation cannot be interrupted. within a certain period of time, only one process code can be executed on the CPU. in the system, sometimes in order to smoothly use and protect shared resources, we put forward the concept of signal. suppose we want to use a printer. If two processes are output to the printer at the same time, what is the final result. to deal with this situation, the POSIX standard puts forward the concepts of the famous semaphores and the unknown semaphores. Since Linux only implements the unknown semaphores, we will only introduce the unknown semaphores here. the use of semaphores is mainly used to protect shared resources, so that resources are owned by only one process at a time. therefore, we can use a signal lamp. when the traffic signal value is a certain value, it indicates that the resource cannot be used at this time. otherwise, the table is displayed. to provide efficiency, the system provides the following functions:
The functions of POSIX's unknown semaphores include the following:

# Include

Int sem_init (sem_t * sem, int pshared, unsigned int value );
Int sem_destroy (sem_t * sem );
Int sem_wait (sem_t * sem );
Int sem_trywait (sem_t * sem );
Int sem_post (sem_t * sem );
Int sem_getvalue (sem_t * sem );

Sem_init creates a signal lamp and initializes the value as value. pshared determines whether the semaphore can be shared among several processes. currently, Linux does not implement shared traffic signals between processes, so this value can only be 0. sem_destroy is used to delete traffic signals. the sem_wait call will block the process until the traffic signal value is greater than 0. when this function returns, it will automatically set the value of the signal. the opposite of sem_post and sem_wait is to add the content of the signal lamp and send a signal to wake up the waiting process .. sem_trywait is the same as sem_wait, but it is not blocked. If the signal light value is 0, EAGAIN is returned, indicating to retry later. sem_getvalue to get the signal light value.
Because Linux does not support it, we cannot use the source program to explain it.
These functions are quite simple to use. for example, we have a program to print two pages to a system printer. first, we create a signal lamp and set its initial value to 1, which indicates that a resource is available. then a process calls sem_wait because the signal light value is 1 at this time, so this function returns, the printer starts printing, and the signal light value is 0. if the second process is to be printed, when sem_wait is called, the traffic signal is blocked because the value of the signal lamp is 0 and the resource is unavailable. when the printing of the first process is complete, the value of the sem_post signal is 1. At this time, the system notifies the second process, so the sem_wait of the second process is returned. the second process is printed.
However, we can use threads to solve this problem. what is thread. compile the program that contains the above functions and add-lrt to connect to librt. so Library
2. To solve the problem above, we can also use the System V semaphore. fortunately, Linux implements the System V semaphore. in this way, we can use an instance to explain. the main functions of System V semaphores are as follows.

# Include
# Include
# Include

Key_t ftok (char * pathname, char proj );
Int semget (key_t key, int nsems, int semflg );
Int semctl (int semid, int semnum, int cmd, union semun arg );
Int semop (int semid, struct sembuf * spos, int nspos );

Struct sembuf {
Short sem_num;/* use that signal */
Short sem_op;/* operations */
Short sem_flg;/* operation flag */
};


The ftok function creates a keyword Based on pathname and proj. semget creates a semaphore. ID of the returned signal when the call succeeds. The key is a keyword, which can be created using ftok or IPC_PRIVATE, indicating that a keyword is selected by the system. nsems indicates the number of signals we have created. semflg is the created permission flag, which is the same as the one used to create a file.
Semctl controls semaphores. semid indicates the signal to be operated, semnum indicates the number of signals, and cmd indicates the Operation Command. the two commonly used values are SETVAL (set the semaphore value) and IPC_RMID (delete the semaphore ). arg is a parameter for cmd.
Semop is a function for signal operations. semid indicates the signal, spos indicates the operation to be performed, and nspos indicates the number of arrays. if sem_op is greater than 0, add sem_op to the semaphore value and wake up the process waiting for the signal to increase. if it is 0, when the semaphore value is 0, the function returns, otherwise it will be blocked until the semaphore value is 0. if it is less than 0, the function determines that the semaphore value is added with this negative value. if the result is 0, wake up the process waiting for the semaphore to 0, if the small function and the 0 function are blocked. if the value is greater than 0, this value is subtracted from the semaphore and the result is returned.
The following example shows how to use these functions. This program uses standard error output instead of the printer.

# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include

# Define PERMS S_IRUSR | S_IWUSR

Void init_semaphore_struct (struct sembuf * sem, int semnum,
Int semop, int semflg)
{
/* Initial traffic signal structure */
Sem-> sem_num = semnum;
Sem-> sem_op = semop;
Sem-> sem_flg = semflg;
}

Int del_semaphore (int semid)
{
/* The signal light is not deleted as the program ends. If not, change 1 to 0)
You can use the ipcs command to view the signal lights, and use ipcrm to delete the signal lights
*/
# If 1
Return semctl (semid, 0, IPC_RMID );
# Endif
}

Int main (int argc, char ** argv)
{
Char buffer [MAX_CANON], * c;
Int I, n;
Int semid, semop_ret, status;
Pid_t childpid;
Struct sembuf semwait, semsignal;

If (argc! = 2) | (n = atoi (argv [1]) <1 ))
{
Fprintf (stderr, "Usage: % s number \ n \ a", argv [0]);
Exit (1 );
}

/* Use IPC_PRIVATE to create a keyword selected by the system */
/* The initial value of the signal lamp after creation is 0 */
If (semid = semget (IPC_PRIVATE, 1, PERMS) =-1)
{
Fprintf (stderr, "[% d]: Acess Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
Exit (1 );
}

/* Semwait requires resource operations (-1 )*/
Init_semaphore_struct (& semwait, 0,-, 0 );

/* Semsignal is the operation to release resources (+ 1 )*/
Init_semaphore_struct (& semsignal, 0, 0 );

/* There is a system resource at the beginning (a standard error output )*/
If (semop (semid, & semsignal, 1) =-1)
{
Fprintf (stderr, "[% d]: Increment Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
If (del_semaphore (semid) =-1)
Fprintf (stderr, "[% d]: Destroy Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
Exit (1 );
}

/* Create a process chain */
For (I = 0; I if (childpid = fork () break;

Sprintf (buffer, "[I = % d] --> [Process = % d] --> [Parent = % d] --> [Child = % d] \ n ",
I, getpid (), getppid (), childpid );
C = buffer;

/* The resource is required to enter the atomic operation */
While (semop_ret = semop (semid, & semwait, 1) =-1) & (errno = EINTR ));
If (semop_ret =-1)
{
Fprintf (stderr, "[% d]: Decrement Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
}
Else
{
While (* c! = '') Fputc (* c ++, stderr );
/* The atomic operation is complete. release resources quickly */
While (semop_ret = semop (semid, & semsignal, 1) =-1) & (errno = EINTR ));
If (semop_ret =-1)
Fprintf (stderr, "[% d]: Increment Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
}

/* When we fail to ask the signal lights of other processes, we have deleted the signal lights */
While (wait (& status) =-1) & (errno = EINTR ));
/* The signal light can only be deleted once */
If (I = 1)
If (del_semaphore (semid) =-1)
Fprintf (stderr, "[% d]: Destroy Semaphore Error: % s \ n \ ",
Getpid (), strerror (errno ));
Exit (0 );
}

The main purpose of a traffic signal is to protect critical resources (only owned by one process at a time ).
3. In order to facilitate communication between processes, SystemV provides functions for communication between processes. This is the message queue.

# Include
# Include
# Include

Int msgget (key_t key, int msgflg );
Int msgsnd (int msgid, struct msgbuf * msgp, int msgsz, int msgflg );
Int msgrcv (int msgid, struct msgbuf * msgp, int msgsz,
Long msgtype, int msgflg );
Int msgctl (Int msgid, int cmd, struct msqid_ds * buf );

Struct msgbuf {
Long msgtype;/* Message Type */
.../* Other data type */
}

The msgget function is the same as the semget function and returns a Message Queue flag. msgctl and semctl control messages. the msgsnd and msgrcv functions are used for message communication. msgid indicates the Message Queue that is accepted or sent. msgp is the content that is accepted or sent. msgsz indicates the Message Size. the msgbuf structure contains at least one msgtype. other components are user-defined. the sending function msgflg indicates the operation when the buffer is used up. the acceptance function indicates the processing when no message is received. generally 0. the receiving function msgtype indicates the operation to receive messages.
If msgtype = 0, the first message in the message queue is received. the first message whose type is greater than 0 in the receiving queue is equal to this value. the minimum number of messages in a message queue smaller than or equal to the absolute value of msgtype. we use an instance to explain Process Communication. the following program consists of a server and a client. run the server first and then the client.
Server. c

# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include

# Define MSG_FILE "server. c"
# Define BUFFER 255.
# Define PERM S_IRUSR | S_IWUSR

Struct msgtype {
Long mtype;
Char buffer [BUFFER + 1];
};

Int main ()
{
Struct msgtype msg;
Key_t key;
Int msgid;

If (key = ftok (MSG_FILE, 'A') =-1)
{
Fprintf (stderr, "Creat Key Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}

If (msgid = msgget (key, PERM | IPC_CREAT | IPC_EXCL) =-1)
{
Fprintf (stderr, "Creat Message Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}

While (1)
{
Msgrcv (msgid, & msg, sizeof (struct msgtype), 1, 0 );
Fprintf (stderr, "Server Receive: % s \ n", msg. buffer );
Msg. mtype = 2;
Msgsnd (msgid, & msg, sizeof (struct msgtype), 0 );
}
Exit (0 );
}


--------------------------------------------------------------------------------

Client (client. c)

# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Define MSG_FILE "server. c"
# Define BUFFER 255.
# Define PERM S_IRUSR | S_IWUSR

Struct msgtype {
Long mtype;
Char buffer [BUFFER + 1];
};

Int main (int argc, char ** argv)
{
Struct msgtype msg;
Key_t key;
Int msgid;

If (argc! = 2)
{
Fprintf (stderr, "Usage: % s string \ n \ a", argv [0]);
Exit (1 );
}

If (key = ftok (MSG_FILE, 'A') =-1)
{
Fprintf (stderr, "Creat Key Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}

If (msgid = msgget (key, PERM) =-1)
{
Fprintf (stderr, "Creat Message Error: % s \ a \ n", strerror (errno ));
Exit (1 );
}

Msg. mtype = 1;
Strncpy (msg. buffer, argv [1], BUFFER );
Msgsnd (msgid, & msg, sizeof (struct msgtype), 0 );
Memset (& msg, '', sizeof (struct msgtype ));
Msgrcv (msgid, & msg, sizeof (struct msgtype), 2, 0 );
Fprintf (stderr, "Client receive: % s \ n", msg. buffer );
Exit (0 );
}

Note that the Message Queue created by the server is not deleted at the end. You need to use the ipcrm command to delete the message queue.
4. SystemV shared memory another way to communicate with processes is to use shared memory. SystemV provides the following functions to implement shared memory.

# Include
# Include
# Include

Int shmget (key_t key, int size, int shmflg );
Void * shmat (int shmid, const void * shmaddr, int shmflg );
Int shmdt (const void * shmaddr );
Int shmctl (int shmid, int cmd, struct shmid_ds * buf );

There is no explanation for shmget and shmctl. size is the size of the shared memory. the shmat is used to connect to the shared memory. shmdt is used to disconnect the shared memory. do not be intimidated by shared memory words. Shared Memory is easy to implement and use. shmaddr and shmflg can be replaced by 0. before using a shared memory, we call shmat to get the starting address of the shared memory. After using the shared memory, we use shmdt to disconnect the memory.

# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include

# Define PERM S_IRUSR | S_IWUSR

Int main (int argc, char ** argv)
{

Int shmid;
Char * p_addr, * c_addr;
If (argc! = 2)
{
Fprintf (stderr, "Usage: % s \ n \ a", argv [0]);
Exit (1 );
}

If (shmid = shmget (IPC_PRIVATE, 1024, PERM) =-1)
{
Fprintf (stderr, "Create Share Memory Error: % s \ n \ a", strerror (errno ));
Exit (1 );
}
If (fork ())
{
P_addr = shmat (shmid, 0, 0 );
Apsaradb for memset (p_addr, '', 1024 );
Strncpy (p_addr, argv [1], 1024 );
Exit (0 );
}
Else
{
C_addr = shmat (shmid, 0, 0 );
Printf ("Client get % s", c_addr );
Exit (0 );
}
}

This program is a parent process that writes parameters to the shared memory, and then the sub-process reads the content. Finally, we need to use ipcrm to release resources. First, find the ID with ipcs and then delete it with ipcrm shm ID.
Postscript:
Process Communication (IPC) is the basis of network programs. In many network programs, the concept and knowledge of Process Communication are widely used. in fact, Process Communication is a very complicated thing. I will just give a brief introduction here. if you want to learn more about Process Communication, the best way is to constantly write programs and read online manuals. now you have a lot of knowledge on the network for reference. unfortunately, most of the information I see is written in English. if you find a Chinese version, please let me know as soon as possible. thank you!

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.