Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2224299
  • 博文数量: 287
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2130
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-31 14:30
个人简介

自己慢慢积累。

文章分类

全部博文(287)

分类: LINUX

2017-02-14 15:12:20

在linux 系统中 使用os.fork 新建一个子进程,11秒后杀掉该子进程
新建的子进程不受父进程的影响,即使父进程结束了,子进程仍然继续
记得要在子进程中写退出命令 exit() , 否则会走父进程结束。

点击(此处)折叠或打开

  1. import os
  2. import time
  3. import signal
  4. def child_process():
  5.     a = 0
  6.     for a in range(0,100):
  7.         time.sleep(1)
  8.         print ("I am the child process and my PID is: %d" % os.getpid())

  9.     print ("the child is exiting.")
  10.     exit()

  11. def parent_process():

  12.     print ("I am the parent process whit PID : %d" % os.getpid())

  13.     childId = os.fork()

  14.     if childId == 0:
  15.         #在子进程中
  16.         child_process()
  17.     else:
  18.         #在父进程中
  19.         print ("inside the parent process")
  20.         print ("my child's pid is : %d" % childId)

  21.     print("exit parent function")
  22.     return childId
  23.     print('-------')

  24. def kill_pr(childId):
  25.     os.kill(childId,signal.SIGKILL)
执行结果是:

点击(此处)折叠或打开

  1. [root@webServer zjx]# python test.py 
    I am the parent process whit PID : 5799
    inside the parent process
    my child's pid is : 5800
    exit parent function
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
    I am the child process and my PID is: 5800
  2. [root@webServer zjx]#

阅读(1374) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~