得到错误: 在子文件中的第37行添加“ labpm3.py”
print("I'm child pid:", os.getpid(), "my next bro is:", nextS)
NameError:未定义名称“ nextS”。
我想知道如何正确定义全局变量,在此先感谢您的反馈
import os, time, sys, signal
children = []
count = 0
def parent(nc, numiter):
nextS = os.getppid()
i = 0
while i < nc:
i+= 1
newpid = os.fork()
if newpid == 0:
child(i)
else:
nextS = newpid
children.append(nextS)
i = 0
while i < numiter:
os.kill(nextS, signal.SIGALRM)
time.sleep(1)
signal.signal(signal.SIGALRM, handler_parent)
i+=1
i = 0
while i < nc:
os.kill(children[i], signal.SIGUSR1)
(pid, sts) = os.waitpid(children[i], 0)
print(pid, os.WEXITSTATUS(sts))
i+=1
def child(number):
global nextS
global count
print("I'm child pid:", os.getpid(), "my next bro is:", nextS)
signal.signal(signal.SIGALRM, handler)
signal.signal(signal.SIGUSR1, handler2)
while True:
time.sleep(10)
def handler(signum, frame):
global nextS
global count
count += 1
print("I'm child pid:", os.getpid(), "sending signal to:", nextS)
os.kill(nextsibl, signal.SIGALRM)
def handler2(signum, frame):
global nextS
global count
sys.exit(count)
def handler_parent(signum, frame):
global count
global nextS
try:
numchild = int(sys.argv[1])
numiter = int(sys.argv[2])
except:
print ('First parameter must be a number', sys.argv[1])
print ('Second parameter must be a number', sys.argv[2])
parent(numchild,numiter)
答案 0 :(得分:0)
首先,您应该在方法外部定义变量。例如:
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
输出:
Inside add(): 2
In main: 2
有关https://www.programiz.com/python-programming/global-keyword
的更多信息