Python Forking: Why Wait for User Input?

  • Context: Python 
  • Thread starter Thread starter daniel_i_l
  • Start date Start date
  • Tags Tags
    Python
Click For Summary
SUMMARY

The discussion centers on the behavior of Python's process forking and its interaction with user input. When a process is forked using os.fork(), the original program's waiting for user input via raw_input() can prevent output from the forked process from displaying until a newline character is printed. This is due to the way standard output buffering works in Python, particularly when using a comma in the print statement, which keeps the output in the buffer. The issue is related to how threads and processes manage access to shared memory, leading to potential output delays.

PREREQUISITES
  • Understanding of Python 2.x syntax, particularly print and raw_input()
  • Familiarity with process management in Python using os.fork()
  • Knowledge of output buffering behavior in Python
  • Basic concepts of threading and process synchronization
NEXT STEPS
  • Research Python 2.x output buffering and how to manage it
  • Learn about process synchronization techniques in Python
  • Explore the differences between threads and processes in Python
  • Investigate the use of threading.Lock for managing shared resources
USEFUL FOR

Python developers, particularly those working with process management and concurrency, as well as anyone looking to understand output behavior in multi-threaded or multi-process applications.

daniel_i_l
Gold Member
Messages
864
Reaction score
0
For some reasons, if I fork a process (or start a thread) in python and let the original program wait for user input, the the forked process doesn't print anything to the screen until the newline character is printed. For example (i used '----' instead of indent):
...
ret = os.fork()
if ret == 0:
----print 'test',
else:
----data = raw_input('input: ')
doesn't print any thing to the screen. But if the 3rd line is instead
print 'test' (without comma)
then it does.
Why is this?
Thanks
 
Technology news on Phys.org
I'm no expert in this, but this reminds me of mutex situation.

Often in programs, different threads or processes use the same memory, so in order to avoid corruption, when a piece of code accesses this memory, it locks it to other code until its done.

This sounds exactly to be the case with your console you are running your code on. Threads and processes need to wait their turn, but I could be wrong, but to me this most likely seems to be the case.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
Replies
17
Views
10K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K