Basic Article 5: apue chap15 inter-process communication

Source: Internet
Author: User
0. preface this article mainly describes apue chapter15's
15.1 introduction 15.2 Pipelines
According to the summary in section 15.11, we can see that we should focus on learning how to use pipelines. 15.1 IntroductionInter-process communication IPC: inter-process communication actually refers to message transmission between processes. 15.2 Pipelines1. Limitations of pipelines: 1) Half Duplex 2) can only be used between processes with common ancestor. Generally, an MPS queue is created by a process and then called by the fork process. The MPs queue can be used between parent and child processes. When one end of the MPs queue is closedThe following two rules take effect: 1) when a write end is read and all data is read, read returns 0 to indicate that the end of the file is reached. 2) When writing a read-end closed pipeline, the sigpipe signal is generated. If this signal is ignored or captured and returned from its handler, write returns-1 and errno is set to epipe.
/* UNP chap 15-1 creates an pipeline from the parent process to the child process, and the parent process transmits data to the child process through this pipeline */
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/types. h>
# Include <fcntl. h>
# Include <stdlib. h>
# Define maxline 200
Int main (void)
{
Int N;
Int FD [2];
Pid_t PID;
Char line [maxline];
If (pipe (FD) <0)
Printf ("pipe error \ n ");
If (pid = fork () <0)
Printf ("fork error \ n ");
Else if (pid> 0 ){
Close (FD [0]);
Write (FD [1], "Hello, world", maxline );
} Else {
Close (FD [1]);
N = read (FD [0], line, maxline );
Write (stdout_fileno, line, N );
}
Exit (0 );
}
/* UNP chap 15-2 copy the file to the paging Program */

# Include <string. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/types. h>
# Include <fcntl. h>
# Include <stdlib. h>
# Include <sys/Wait. H>
# Define maxline 5000
# Define FILENAME "/home/hpnl/downloads/epoll_io1.c"
Int main (void)
{
Int N;
Int FD [2];
Pid_t PID;
File * FP;
Char * pager, * argv0;
Char line [maxline];
If (FP = fopen (filename, "R") = NULL ){
Printf ("fopen error \ n ");
}
If (pipe (FD) <0)
Printf ("pipe error \ n ");
If (pid = fork () <0)
Printf ("fork error \ n ");
Else if (pid> 0 ){
Close (FD [0]);
While (fgets (line, maxline, FP )! = NULL ){
N = strlen (line );
If (write (FD [1], line, n )! = N)
Printf ("write error \ n ");
}
Close (FD [1]);
If (waitpid (PID, null, 0) <0)
Printf ("waitpid error \ n ");
Exit (0 );
} Else {
Close (FD [1]);
If (FD [0]! = Stdin_fileno ){
If (dup2 (FD [0], stdin_fileno )! = Stdin_fileno)
Printf ("dup2 error \ n ");
Close (FD [0]);
}

If (PAGER = getenv ("pager") = NULL)
Pager = "/bin/more ";
If (argv0 = strrchr (PAGER ,'/'))! = NULL)
Argv0 ++;
Else
Argv0 = pager;
If (execl (PAGER, argv0, (char *) 0) <0)
Printf ("execl error \ n ");
}
Exit (0 );
}

Running result: During GDB debugging, enter the sub-process set follow-fork-mode child to run more, and (GDB) Q will display the following prompt: this is in line with rule 2: When writing a read end closed pipeline, a signal sigpipe is generated. If this signal is ignored or captured and returned from its handler, write returns-1 and errno is set to epipe. To fully understand the MPs queue, I have found some detailed example 1 on the Internet:
/* If the parent process does not close the write end of the pipeline, even if the child process closes the write end of the pipeline, it will still block the read
1) when reading a write end closed pipeline, all data is read, and read returns 0 to indicate that the end of the file is reached.
This program can describe this point well. When close (PFD [1]) in the parent is commented out, the program will be blocked */

# Include <stdio. h>
# Include <unistd. h>
# Include <stdlib. h>
# Include <sys/Wait. H>
Int main (INT argc, const char ** argv)
{
Int Len;
Pid_t PID;
Int PFD [2];
Char buffer [1024] = {0 };
 

If (pipe (PFD) <0 ){
Printf ("pipe error \ n ");
Exit (0 );
}
 
If (pid = fork () <0 ){
Printf ("fork error \ n ");
Exit (0 );
}
 
If (pid = 0) {/* sub-process */
Close (PFD [1]);
While (LEN = read (PFD [0], buffer, 1023)> 0 ){
Buffer [Len] = '\ 0 ';
Printf ("Len = % d, % s", Len, buffer );
}
} Else {/* parent process */
Close (PFD [0]);
Write (PFD [1], "Hello \ n", 6 );
// Close (PFD [1]);
Wait (0 );
}
Return 0;
}
Example 2:
/* 1 only when the reference count of the MPs queue write end changes to 0 will the MPs queue write end be closed.
2. After the process ends, the opened files are automatically closed.
3 if the parent process exits first and does not call wait to wait for the child process, the child process will become a zombie process */
# Include <sys/Wait. H>
# Include <stdio. h>
# Include <unistd. h>
# Include <stdlib. h>
 
Int main (INT argc, const char ** argv)
{
Int Len;
Pid_t PID;
Int PFD [2];
Char buffer [1024] = {0 };
 
If (pipe (PFD) <0 ){
Printf ("pipe error \ n ");
Exit (0 );
}
 
If (pid = fork () <0 ){
Printf ("fork error \ n ");
Exit (0 );
}
 
If (pid = 0) {/* sub-process */
Write (PFD [1], "Hello \ n", 6 );
// Close (PFD [1]);
Sleep (2 );
} Else {/* parent process */
Close (PFD [1]);
While (LEN = read (PFD [0], buffer, 1023)> 0 ){
Buffer [Len] = '\ 0 ';
Printf ("Len = % d, % s", Len, buffer );
}
Printf ("read done \ n ");
Wait (0);/* wait until the sub-process exits to see the effect */
}
Return 0;
}
15.3 popen and pclose FunctionsA common operation is to create a pipeline to connect to another process and then read its output or send data to its input. Therefore, the standard I/O Library provides two functions: popen and pclose. 15.4 collaborative process 15.5 FIFOFIFO is also known as a named pipe. Through FIFO, unrelated processes can also exchange data. 15.6 xsi IPC 15.7 Message QueueA message queue is a chain table of messages. It is stored in the kernel and identified by the Message Queue identifier. 15.8 semaphoresSemaphore is a counter used by multiple processes to access Shared data objects. Semaphores are actually synchronization primitives, rather than IPC, and are often used for Synchronous access to shared resources. The kernel sets a semid_ds structure for each semaphore set.
Struct semid_ds {
Struct ipc_perm sem_perm
Unsigned short sem_nsems;
Time_t sem_otime;
Time_t sem_ctime;
.........

}

15.9 shared storage Shared storage allows two or more processes to share a given storage zone.. Because data does not need to be copied between the client process and the server process, this is the fastest IPC. The only trick to master when using shared storage is to connect multiple processes to a given storage zone. Synchronous access. Generally, SemaphoresUsed to synchronize shared storage access.
 /* One shmid data structure for each shared memory segment in the system. */        struct shmid_ds {                struct ipc_perm shm_perm;        /* operation perms */                int     shm_segsz;               /* size of segment (bytes) */                time_t  shm_atime;               /* last attach time */                time_t  shm_dtime;               /* last detach time */                time_t  shm_ctime;               /* last change time */                unsigned short  shm_cpid;        /* pid of creator */                unsigned short  shm_lpid;        /* pid of last operator */                short   shm_nattch;              /* no. of current attaches */                                                 /* the following are private */                unsigned short   shm_npages;     /* size of segment (pages) */                unsigned long   *shm_pages;      /* array of ptrs to frames -> SHMMAX */                 struct vm_area_struct *attaches; /* descriptors for attaches */        };
15.10 customer process-server process attributes Conclusion 15.11This chapter details the various forms of inter-process communication: pipelines, named pipelines (FIFO), and three other IPC forms (usually called xsi IPC), namely message queues, semaphores, and shared storage. Make the following suggestions: 1) Learn to use pipelines and FIFOBecause these two basic technologies can still be effectively used in a large number of applications. 2) In new applications, try Avoid using message queues and semaphoresBut should consider Full Duplex pipe and record lockThey are much simpler to use.

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.