在Python中os.fork()产生子进程的例子

yipeiwu_com6年前Python基础

例1

import os
print 'Process (%s) start...' %os.getpid()
pid = os.fork()
if pid==0:
  print 'I am child (%s) and my father is %s.'%(os.getpid(),os.getppid())
else:
  print 'I (%s) just created a child process (%s).' %(os.getpid(),pid)

加载os模块后,首先os.fork()函数生成一个子进程,返回值pid有两个,一个为0,

用以表示在子进程当中,一个是大于0的整数,表示在父进程,这个常数正是子进程的pid.

if pid == 0,在子进程当中os.getpid()是子进程的pid,os.getppid()是父进程pid

if pid >0 ,在父进程当中,os.getpid()是父进程的pid,os.fork()返回的就是子进程的pid

例2

import os 

def child(): 
  print 'A new child:', os.getpid() 
  print 'Parent id is:', os.getppid() 
  os._exit(0) 

def parent(): 
  while True: 
    newpid=os.fork() 
    print newpid 
    if newpid==0: 
      child() 
    else: 
      pids=(os.getpid(),newpid) 
      print "parent:%d,child:%d"%pids 
      print "parent parent:",os.getppid()     
    if raw_input()=='q': 
      break 

parent() 

以上这篇在Python中os.fork()产生子进程的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python下调用pytesseract识别某网站验证码的实现方法

一、pytesseract介绍 1、pytesseract说明 pytesseract最新版本0.1.6,网址:https://pypi.python.org/pypi/pytesser...

Python 12306抢火车票脚本 Python京东抢手机脚本

本文实现12306抢火车票/京东抢手机示例,具体如下: #12306秒抢Python代码 from splinter.browser import Browser x = Brows...

Python如何实现MySQL实例初始化详解

前言 相信每位程序员对mysql应该都不陌生,MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。我们在日常开发中少不了要接触mys...

Python中的Numpy矩阵操作

Numpy 通过观察Python的自有数据类型,我们可以发现Python原生并不提供多维数组的操作,那么为了处理矩阵,就需要使用第三方提供的相关的包。 NumPy 是一个非常优秀的提...

解决PyCharm同目录下导入模块会报错的问题

在PyCharm2017中同目录下import其他模块,会出现No model named ...的报错,但实际可以运行 这是因为PyCharm不会将当前文件目录自动加入source_p...