Defect (1) pipe deadlock

Source: Internet
Author: User

Author: Lin Haifeng
URL:Http://blog.csdn.net/linyt/archive/2008/09/26/2983960.aspx
[Note]: The copyright of this article is owned by the author and can be freely reproduced, but cannot be partially reproduced. Please submit it for any commercial use.

 

With the approaching work pressure and project time, I think there will always be bugs in one way or another written by many programmers. What's more, it can be hidden for several months or a year, at the time of the outbreak, the loss was very heavy. It is true that when there is code, there is a place where bugs are hidden. This sentence is not without reason. For developers, a bug in their own code is nothing more than a buzz. Due to work reasons, the system code bug is being modified recently and some code quality check work is required. Today, I am very busy with my work, but I feel very successful because I found bugs hidden for a long time. Originally, I solved another bug. During the verification process, due to a small problem with the current version, a certain path failed and a large number of error messages were generated. These error messages let me find the nest of this bug.

 

I will use an example to illustrate my problems. Below is the code with a bug (Python language). The code I work with is not to run CAT test, but to others.

 

  1. #! /Usr/bin/Python
  2. Import OS
  3. Import subprocess
  4. Def main ():
  5. Proc = subprocess. popen ("cat test ",
  6. Shell = true,
  7. CWD = '.',
  8. Stdin = subprocess. pipe,
  9. Stdout = subprocess. pipe,
  10. Stderr = subprocess. Pipe );
  11. Retcode = Proc. Wait ();
  12. Print 'ret code = ', retcode
  13. Print 'loginfo: ', Proc. stdout. Read (512)
  14. If retcode! = 0:
  15. Print 'errmsg: ', Proc. stderr. Read ()
  16. If _ name _ = '_ main __':
  17. Main ()

I believe that friends with Linux experience will soon be able to clearly understand this small program (obviously, the program I work on won't be so simple, except that main generates a sub-process to run a command, do other things, skip the code here ).

 

The above code is as follows:

Generates a child process to execute the "cat test" command. The parent process waits for it to end. To obtain the output of the sub-process, stderr is specified as pipe when the sub-process is created.

 

Bug appearance:

During the test, I found that the software package was stuck during the running process, that is, it was neither an error nor ended. I want to write reports for my work, so I need to analyze whether such results are caused by my code. (It is definitely not my problem, the code I wrote is different from the code of this software package ). The code is quite long, but with my experience, I quickly tracked its call chain. I feel like it tells me that it is very likely that a problem occurs in the wait function, but I don't know why, this is not what I expected. Because I think the above Code is well written and quite elegant. Then, Google, and then I started to look dumb. The e-text line "dead lock on wait" attracted me. The reason is as follows:

When the created sub-process starts running, its stdout and stderr have been redirected to the pipeline. Pipelines in Linux have a certain capacity. When the channel is full, the write operation will block the pipeline until it can be written. In the above Code, after the parent process creates a child process, it does not perform read operations on the pipelines they communicate with, but calls wait to wait until the child process ends. If the child process writes the output to the MPs queue, the child process is expected to clear the output as soon as possible, and the parent process wants the child process to end as soon as possible. In this way, the deadlock we learned in the OS has finally appeared.

It is quite easy to test the code above. just create a large file named test. The program is stuck there.

If a problem is found, you can find a way to understand the problem. When the sub-process ends, you must clear the contents of the MPs Queue (read ). The popen class has a method called communicate to obtain standard output and error output of sub-processes. Although this method can solve the pressing problem, it is not available. This is because this method gets the output of the sub-process at one time and stores it in the memory. If the sub-process generates a large amount of output or error information, there are still many problems in the program. It is better to get the output of sub-processes in a timely manner and in multiple stages. This frees you from occupying a large amount of memory space. So I chose select to process the output of sub-processes. And achieve the following goals:

1. Clear the contents of the MPs queue in a timely manner.

Since the parent process can do other tasks only after the child process is completed, it is easy to clean up the pipeline in time. There are many methods to implement Linux.

2. You must be aware of the end of the sub-process before cleaning the MPs queue.

If the sub-process output can be read in a timely manner, reading the output EOF indicates that the sub-process has ended.

 

According to this idea, I use select to process the output of sub-processes. The changed code is as follows:

 

  1. #! /Usr/bin/Python
  2. Import OS
  3. Import subprocess
  4. Import select
  5. Def main ():
  6. Proc = subprocess. popen ("cat test ",
  7. Shell = true,
  8. CWD = '.',
  9. Stdin = subprocess. pipe,
  10. Stdout = subprocess. pipe,
  11. Stderr = subprocess. Pipe)
  12. First_out =''
  13. First_err =''
  14. Rest_out =''
  15. Rest_err =''
  16. Read_lename = 1024
  17. Select_rfds = [Proc. stdout, Proc. stderr]
  18. While Len (select_rfds)> 0:
  19. (Rfds, wfds, efds) = select. Select (select_rfds, [], [])
  20. If Proc. stdout in rfds:
  21. If Len (first_out) = 0:
  22. First_out = Proc. stdout. Read (read_len)
  23. Rest_out = first_out
  24. Else:
  25. Rest_out = Proc. stdout. Read (read_len)
  26. If Len (rest_out) = 0:
  27. Select_rfds.remove (Proc. stdout)
  28. If Proc. stderr in rfds:
  29. If Len (first_err) = 0:
  30. First_err = Proc. stderr. Read (read_len)
  31. Rest_err = first_err
  32. Else:
  33. Rest_err = Proc. stderr. Read (read_len)
  34. If Len (rest_err) = 0:
  35. Select_rfds.remove (Proc. stderr)
  36. Retcode = Proc. Wait ()
  37. Print 'ret code = ', retcode
  38. Print 'loginfo: ', first_out
  39. If retcode! = 0:
  40. Print 'errmsg: ', first_err
  41. If _ name _ = '_ main __':
  42. Main ()

Because program output and error messages may be staggered, select also checks whether they have readable data. If yes, it will be processed. When the child process ends, both the standard output and the error output close the MPs queue. Then, when the parent process reads data to the MPs queue, it reads the EOF (File Terminator ). In this way, the parent process is notified of the completion of the Child process. And call wait to obtain its return value and protect it from freezing.

 

Summary:

Do not make any assumptions about others' programs. Looking back at the first code, we will find that the output of the sub-process will not exceed 512 bytes. This assumption is incorrect, because you cannot determine what command parameters will be passed to the subprocess. popen class. Even if this is done, the number of output bytes cannot be determined. Therefore, when writing code, you should make a general idea about calling the program:

1. The operation is successful. Only standard output is available, but the data volume cannot be determined.

2. Failed to run, only error output, large or small data volume

3. Failed to run. The standard output and error output are staggered. You cannot determine who is the first and the number of times.

 

Remember: you cannot make any assumptions about the program. Just as it cannot be assumed that the file is opened successfully and the content is allocated successfully, the return value of the function must be processed fairly.

 

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.