关于Python中的os.fork()函数

编程入门 行业动态 更新时间:2024-10-09 21:28:50
本文介绍了关于Python中的os.fork()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只是从python开始,所以我开发了一个简单的程序来生成父进程.这是我到目前为止编写的代码...

I'm just beginning with python and I developed a simple program to fork a parent process. Here's the code I've written so far...

#!/usr/bin/env python import os def child(): print "We are in the child process with PID= %d"%os.getpid() def parent(): print "We are in the parent process with PID= %d"%os.getpid() newRef=os.fork() if newRef==0: child() else: print "We are in the parent process and our child process has PID= %d"%newRef parent()

据我了解,代码应首先调用父进程并显示其PID.然后,调用os.fork()并创建父进程的副本,并且由于我们已经在父进程中,因此newRef变量应包含一个正值,而我的代码的else部分为应该执行的那个.我的问题是:为什么我的代码的if部分不应该执行,为什么代码随后会启动以调用child()函数.

From what I understand, the code should begin by calling the parent process and display its PID. Afterwards, the os.fork() is called and it creates a copy of the parent process, and since we are already in the parent process, the newRef variable should contain a value that is positive and the else part of my code is the one that should be executed. My question is that: why did the code initiate to call the child() function afterwards although the if part of my code should not execute.

先谢谢您了:)

推荐答案

从fork返回之后,您现在有两个进程在fork之后立即执行代码.

After you return from fork, you now have two processes executing the code immediately following fork.

您的声明:

因为我们已经在父流程中

since we are already in the parent process

只有一半是正确的.返回os.fork后,父进程将继续执行与父进程相同的代码,但是子进程将继续使用相同的局部变量和全局变量执行完全相同的代码,但返回值除外fork.因此,从子进程的角度来看,newRef的值为0,而从父进程的角度来看,newRef的值为正.这两个过程将相应地执行代码.

is only half-true. After os.fork returns, the parent process continues executing the code as the parent process, but the child process continues executing the exact same code with the same local and global variables, with the exception of the return value of fork. So, from the child process's perspective, newRef has the value of 0, and from the parent's perspective, newRef has a positive value. Both processes will execute the code accordingly.

更多推荐

关于Python中的os.fork()函数

本文发布于:2023-07-06 07:45:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Python   os   fork

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!