编写一个程序,在主进程中创建一个子进程,子进程输出“This is the child process!”,主进程输出进程号及子进程号。
时间: 2024-05-10 13:17:24 浏览: 16
以下是使用 Python 语言编写的程序:
```python
import os
def main():
pid = os.fork() # 创建子进程
if pid == 0:
# 子进程
print("This is the child process!")
else:
# 主进程
print(f"Parent process ID: {os.getpid()}")
print(f"Child process ID: {pid}")
if __name__ == '__main__':
main()
```
运行结果类似于:
```
Parent process ID: 1234
Child process ID: 1235
This is the child process!
```
其中,1234 和 1235 分别表示父进程和子进程的进程号。可以看到,子进程先输出了“This is the child process!”,然后父进程输出了进程号信息。