os.fork
来源:互联网 发布:淘宝墙上挂的饰品 编辑:程序博客网 时间:2024/06/05 03:14
python的os module中有fork()函数用于生成子进程,生成的子进程是父进程的镜像,但是它们有各自的地址空间,子进程复制一份父进程内存给自己,两个进程之间的执行是相互独立的,其执行顺序可以是不确定的、随机的、不可预测的,这点与多线程的执行顺序相似。
在我们加载了os模块之后,我们parent函数中fork()函数生成了一个子进程,返回值newpid有两个,一个为0,用以表示子进程,一个是大于0的整数,用以表示父进程,这个常数正是子进程的pid. 通过print语句我们可以清晰看到两个返回值。如果fork()返回值是一个负值,则表明子进程生成不成功(这个简单程序中没有考虑这种情况)。如果newpid==0,则表明我们进入到了子进程,也就是child()函数中,在子进程中我们输出了自己的id和父进程的id。如果进入了else语句,则表明newpid>0,我们进入到父进程中,在父进程中os.getpid()得到自己的id,fork()返回值newpid表示了子进程的id,同时我们输出了父进程的父进程的id. 通过实验我们可以看到if和else语句的执行顺序是不确定的,子、父进程的执行顺序由操作系统的调度算法来决定。
#!/usr/bin/python# -*- coding: UTF-8 -*-import os, sysprint("The child will write text to a pipe and ")print("the parent will read the text written by child...")# file descriptors r, w for reading and writingr, w = os.pipe()print(os.getpid())print("over")processid = os.fork()print(processid)if processid: # This is the parent process # Closes file descriptor w os.close(w) r = os.fdopen(r) print("parent",os.getpid(),os.getppid()) print("Parent reading") str = r.read() print("text =", str) sys.exit(0)else: # This is the child process os.close(r) w = os.fdopen(w, 'w') print("child",os.getpid(),os.getppid()) print("Child writing") w.write("Text written by child...") w.close() print("Child closing") sys.exit(0)
0 0
- os.fork
- python 的os.fork()
- python fork os.pipe()
- python os.fork()
- python os.fork() 循环输出
- Python 使用 os.fork() 创建子进程
- Python 进程,子进程( os.fork() )
- Python之OS模块进程管理介绍--os.fork()
- Python之OS模块进程管理介绍--os.fork()
- 由fork()和vfork()回忆下OS的内存管理
- Mac OS X: 文件图标制作和变更(Resource Fork)
- Python中os.fork()产生子进程
- AttributeError: 'module' object has no attribute 'fork' 切记:windows内核中没有os.fork()函数
- fork
- FORK()
- fork
- fork
- fork()
- 从尾到头打印链表
- struts2 文件下载
- 安装repo
- 制作 cocoa pods 遇到点问题
- Revit开发获取梁的宽和高
- os.fork
- Struts2输出html代码原样输出
- Swift 为Array添加remove方法遇到的问题
- Qt5_QCustomPlot画实时动态曲线(1)
- LeetCode Weekly Contest 28解题思路
- 1234输出不同且不重复的三位数
- 隐藏表格td的线框
- 利用Python建立本地Web服务在Chrome中运行WebGL
- 小白训练营 TEST by 喵仔