python创建进程fork用法

yipeiwu_com5年前Python基础

本文实例讲述了python创建进程fork用法。分享给大家供大家参考。具体分析如下:

#!coding=utf-8
import os ,traceback
import time
'''
fork()系统调用是Unix下以自身进程创建子进程的系统调用,
一次调用,两次返回,如果返回是0,
则是子进程,如果返回值>0,则是父进程(返回值是子进程的pid)
'''
source = 10
i = 0
try:
  print '***********************'
  pid = os.fork()
  #这里会返回两次,所以下面的省略号会输出2次
  print '......'
  if pid == 0:#子进程
    print "this is child process"
    source = source - 1
    print 'child process source is ',source
    time.sleep(10)
    print 'child sleep done'
  else:  #父进程
    print "this is parent process"
    print 'parent process source is ',source
    time.sleep(10)
    print 'parent sleep done'
  print source
except:
  traceback.print_exc()

输出如下:

***********************
......
this is child process
child process source is 9
......
this is parent process
parent process source is 10
child sleep done
9
parent sleep done
10

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python绘图实现显示中文

Python绘图实现显示中文

我们用Python进行数据可视化,绘制各种图形时,往往会遇到明明数据都设置对了,但是在图形上显示不出来。例如绘制直方图,程序如下: plt.hist(roll_list, bins=...

Python中设置变量作为默认值时容易遇到的错误

思考一下下面的代码片段:   def foo(numbers=[]): numbers.append(9) print numbers 在这里,我们定义了一个...

Python GUI Tkinter简单实现个性签名设计

Python GUI Tkinter简单实现个性签名设计

一、Tkinter的介绍和简单教程 Tkinter 是 Python 的标准 GUI 库。Python 使用 Tkinter 可以快速的创建 GUI 应用程序。 由于 Tkinter...

Python BS4库的安装与使用详解

Python BS4库的安装与使用详解

Beautiful Soup 库一般被称为bs4库,支持Python3,是我们写爬虫非常好的第三方库。因用起来十分的简便流畅。所以也被人叫做“美味汤”。目前bs4库的最新版本是4.60。...

Python语言的变量认识及操作方法

今天我给大家介绍的是python中的Number变量,与c++,java有些不同,下面让来为大家介绍: 在python中是不用声明变量类型的,不过在使用变量前需要对其赋值,没有值得变量是...