wait(null)在父进程的位置不同对结果有什么影响,分析原因,用具体代码说明
时间: 2023-06-12 16:02:27 浏览: 42
在父进程中,wait(null)会等待任何一个子进程结束并返回其pid;在子进程中,wait(null)会等待任何一个子进程结束并返回0。因此,在父进程中的wait(null)会阻塞整个进程直到有子进程退出,而在子进程中的wait(null)会仅阻塞子进程本身。具体代码如下:
```python
import os
pid = os.fork()
if pid == 0:
# child process
print("This is child process with pid ", os.getpid())
exit(0)
else:
# parent process
print("This is parent process with pid ", os.getpid())
# Option 1: wait in parent process
pid, status = os.wait()
print("Child process with pid ", pid, " exited with status ", status)
# Option 2: wait in child process
"""
pid = os.wait()
if pid[0] == 0:
print("This is child process with pid ", os.getpid(), " and parent pid ", os.getppid())
else:
print("Parent process with pid ", os.getpid(), " waited for child process with pid ", pid[0], " and exited with status ", pid[1])
"""
```
如果选用Option 1,输出结果为:
```
This is parent process with pid 12345
This is child process with pid 12346
Child process with pid 12346 exited with status 0
```
如果选用Option 2,输出结果为:
```
This is child process with pid 12346
Parent process with pid 12345 waited for child process with pid 12346 and exited with status 0
```