ipython and fork()

I am planning a Python script that'll use os.fork() to create a bunch of child processes to perform some computations. The parent process will block until the children terminate.

The twist is that I need to be able to run the script both from the Unix shell using python and from ipython using %run.

In what manner should the child processes terminate to avoid breaking back into the ipython command prompt? In my experience, sys.exit() won't do.

Answers


The following seems to work:

import os, sys

child_pid = os.fork()
if child_pid == 0:
  print 'in child'
  os._exit(os.EX_OK)
  print 'hm... wasn''t supposed to get here'
else:
  print 'in parent'

The trick is to use os._exit() instead of sys.exit(). The documentation contains the following passage:

Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().


Need Your Help

Windows 8 App reading and/or copying locked file

c# visual-studio windows-8 windows-store-apps

I am writing a Windows 8 App (as the title says) and I want to be able to copy a file used by another program when it is done being written but still being used. Windows Explorer does not allow co...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.