Introduction to Linux process programming (4)

Source: Internet
Author: User
Article title: Linux process programming (4 ). Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Abstract: In this section, we will look at a simple data transfer method, that is, transmitting data through pipelines.
  
4. use pipelines to communicate between processes
  
The operations related to processes are described in the previous sections. we have learned to create a new process, change the execution image of the process, and perform other operations. However, there is still a lack of data exchange between the child process and the parent process, and between the child process and the child process. In this section, we will look at a simple method of data transmission, that is, data transmission through pipelines.
  
The MPs queue allows data to be transmitted between processes in the first-in-first-out mode. the MPs queue also allows the process to be executed synchronously. The traditional method of pipeline is to use a file system as the place to store data. There are two types of pipelines: one is an unknown pipeline, or a famous pipeline, also known as FIFO. A process uses the system call open to open a famous pipeline, and the system call pipe to create an unknown pipeline. A process that uses an unknown pipeline to communicate must be the process that sends a pipe call and its subprocesses. The preceding restrictions are not imposed on processes that communicate with famous pipelines. In the future, all the unknown pipelines are referred to as pipelines. Next, let's take a look at the system call pipe.
  
4.1 pipe system call
  
The system calls pipe to establish pipelines. The declaration format of this call is as follows:
  
?? Int pipe (int filedes [2]);
  
Add the following header file to the program that uses this call:
  
?? # Include
  
An MPs queue has two file descriptors for communication. they direct to the indexing node of an MPs queue. this call places these two file descriptors in the filedes parameter and returns the results. In many systems, pipelines allow two-way data flow, but in general, the file descriptor filedes [0] is used to read data, and filedes [1] is used to write data. If the program is required to be portable, it should be programmed according to the usual usage. When the call is successful, the returned value is 0. If an error is returned,-1 is returned, and the error code errno is set:
  
EMFILE: The process uses too many file descriptors.
ENFILE: The system file table is full.
EFAULT: the filedes parameter is invalid.
The following describes how to operate pipelines:
  
For writing pipelines:
Data written to the MPs queue is arranged in the order of arrival. If the pipeline is full, write to the pipeline is blocked until the data in the pipeline is read by the read operation. For write operations, if the data volume written by one write call is smaller than the pipeline capacity, the write must be completed once, that is, if the remaining capacity of the pipeline is insufficient, write is blocked until the remaining capacity of the MPs queue can be written at one time. If the volume of data written by the write call is greater than the capacity of the MPs queue, the write operation is completed multiple times. If fcntl is used to set the pipeline write port as a non-blocking mode, the pipeline will not block write when it is full, but will only return 0 for write.
  
For read pipelines:
Read operations read data in the order of data arrival. The read data no longer exists in the pipeline, which means that the data cannot be reused in the pipeline. If the MPs queue is empty and the write port of the MPs queue is open, the read operation is blocked until data is written. In one read call, if the data volume in the MPs queue is not enough, read the data based on the actual number and return the actual number of read data values. If the read port uses fcntl to set the non-blocking mode, when the MPs queue is empty, the read call returns 0.
  
Pipe closure:
If the read port of the MPs queue is disabled, the write operation calling process on the MPs queue receives a SIGPIPE signal. Closing the write port is the only way to give the read port a file terminator. After the write port is closed, 0 is returned for the read call on the pipeline. Next let's take a look at the pipe example called by the system. In the following example, the parent process sends a string to the child process through a pipeline. The sub-process displays it:
  
# Include
# Include
# Include
# Include
# Include
Int main ()
{
Int fd [2], cld_pid, status;
Char buf [200], len;
  
If (pipe (fd) =-1)
{
?? Printf ("creat pipe error ");
?? Exit (1 );
}
If (cld_pid = fork () = 0)
{
?? Close (fd [1]);
?? Len = read (fd [0], buf, sizeof (buf ));
?? Buf [len] = 0;
?? Printf ("Child read pipe is -- % s", buf );
?? Exit (0 );
}
Else
{
?? Close (fd [0]);
?? Sprintf (buf, "Parent creat this buff for cld % d", cld_pid );
?? Write (fd [1], buf, strlen (buf ));
?? Exit (0 );
}
}
  
Screen copy of the program execution process:
  
[Root @ wapgw/tmp] #./pipe
[Root @ wapgw/tmp] # Child read pipe is -- Parent creat this buff for cld 5954
[Root @ wapgw/tmp] #
  
4.2 dup system call
  
The system calls dup to copy a file descriptor, that is, copy one of the file descriptor tables in the process u area so that these two items point to the same table item of the system file table at the same time. The declaration format of this call is as follows:
  
?? Int dup (int oldfd );
?? Int dup2 (int oldfd, int newfd );
  
Add the following header file to the program that uses this call:
  
?? # Include
  
The system calls dup to copy the file description specified by the oldfd parameter to the first empty table entry in the process file descriptor table. The system calls dup2 to copy the file description specified by the oldfd parameter to the file descriptor table specified by newfd. The old and new file descriptors can be used interchangeably. They share locks, file pointers, and file statuses. For example, for one of the file descriptors, the system calls lseek to modify the position of the file pointer. for another file descriptor, the file pointer also changes. In fact, we understand how the kernel works, this is easy to understand. Because we know that the file pointer is placed in the system file table. However, these two file descriptors have different close-on-exec flags because they are stored in the file descriptor table.
  
When the call is successful, the returned value is a new descriptor. When an error occurs,-1 is returned, and the corresponding error code errno is set:
  
EBADF: the parameter oldfd is not an opened file descriptor; or the parameter newfd exceeds the allowed value range of the file descriptor.
EMFILE: the number of file descriptors opened by a process has reached the maximum value, but it still attempts to open a new file descriptor.
Let's take a simple example. In this example, we disable the standard output (file descriptor is 1) and copy a file descriptor that opens the common file "output" to the standard output, because file descriptor 1 has just been disabled, the first empty table item in the file descriptor table is 1. Therefore, the content written to the standard output by printf after the program is written to the file output.
  
?? # Include
?? # Include
?? # Include
?? # Include
?? # Include
?? Int main ()
?? {
?? Int fd;
?? If (fd = open ("output", O_CREAT | O_RDWR, 0644) =-1)
?? {
???? Printf ("cannot open output file ");
???? Exit (1 );
??}
?? Close (1);/* close standard output */
?? Dup (fd);/* copy fd to file descriptor 1 */
?? Close (fd);/* It is a good habit to close unused file descriptors instantly */
?? Printf ("This line will write to file ");
?? Exit (0 );
??}
  
Screen copy of the program execution process:
  
?? [Wap @ wapgw/tmp] $ gcc-o dup_test dup_test.c
?? [Wap @ wapgw/tmp] $./dup_test
?? [Wap @ wapgw/tmp] $ more output
?? This line will write to file
?? [Wap @ wapgw/tmp] $
  
Related Article

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.