对于我的操作系统课程,我们尝试使用管道来让两个孩子随机选择两个值并将它们添加为一个Sum,我有一个想法并且近似代码应该是什么但是我一直在局部变量错误和缺少子进程错误。我们的类在VirtualBox中使用Linux版本在终端中运行我们的Python代码。
import os, sys
import random
r0, w0 = os.pipe()
r1, w1 = os.pipe()
def child0():
pid = os.getpid()
random.seed(pid)
v = random.randrange(101)
v1 = str(v)
os.write(w0, v1.encode("utf-8"))
def child1():
pid1 = os.getpid()
random.seed(pid1)
v = random.randrange(101)
v2 = str(v)
os.write(w1, v2.encode("utf-8"))
def main():
paid = os.getppid()
if os.fork() !=0:
print("[",paid, "]: spawning children")
if os.fork() !=0:
#Still In Parent
print("Still In Parent")
else:
cid = os.getpid()
x = child0()
v1 = os.read(r0, 10)
child0()
print("[",cid, "]: picks", int(v1))
else:
print("[",paid, "]: reaping")
cid1 = os.getpid()
z = child1()
v2 = os.read(r1, 20)
child1()
print("[",cid1, "]: picks", int(v2))
print("[",paid, "]: Sum is", int(v1) + int(v2))
main()
答案 0 :(得分:0)
所以......看起来你的代码正在混合子进程和父进程位。
在第28行,你分叉。您检查您是否在孩子或父进程中。这很好。但是在第42行,当你明确地在父进程中时,你表现得像在你的子进程中一样。这是第30行的类似情况。
以下是main
的更好定义:
def main():
paid = os.getppid()
if os.fork() !=0:
print("[",paid, "]: spawning children")
if os.fork() !=0:
#Still In Parent
print("Still In Parent")
print("[",paid,"]: reaping")
v1,v2 = os.read(r0,10),os.read(r1,10)
print "Child 0 picks",int(v1)
print "Child 1 picks",int(v2)
print "sum is: ",int(v1)+int(v2)
else: #Now in child 0...
cid = os.getpid()
child0()
else: #Now in child 1...
cid1 = os.getpid()
child1()
这里的其他代码对我来说并不适用,但它描述了......有点......你做了什么。
import os,random,time
def print_as(le_pid,message):
print("[",le_pid,"]: ",message)
def main():
r0,w0 = os.pipe()
r1,w1 = os.pipe()
if os.fork() != 0:#In main
if os.fork() != 0: #Still in main
pid_main = os.getpid()
print_as(pid_main,"I'm the parent, successfully isolated.")
time.sleep(10) #This is here so that the children can spawn and choose.
print_as(pid_main,"Children spawned, reaping values...")
v0,v1 = os.read(r0,10),os.read(r1,10)
print_as(pid_main,"Received values.")
print_as(pid_main,"Output is: "+str(int(v0)+int(v1)))
else: #In child 0
pid_0 = os.getpid()
print_as(pid_0,"Child 0 successfully spawned.")
random.seed(pid_0)
v = random.randrange(101)
v0 = str(v)
print_as(pid_0,"I'm picking: "+v0)
os.write(w0,v0.encode("utf-8"))
else:#In child 1
pid_1 = os.getpid()
print_as(pid_1,"Child 1 successfully spawned.")
random.seed(pid_1)
v = random.randrange(101)
v1 = str(v)
print_as(pid_1,"I'm picking: "+v1)
os.write(w1,v1.encode('utf-8'))