在 Linux 应用程序中使用 for 语句编写一个循环,使父进程能够 循环创建 10 个子进程,每个子进程在输出自己的 pid 后退出,父进程等待所有子进程 结束后再退出。
时间: 2024-03-23 16:40:35 浏览: 144
可以使用如下的Shell脚本来实现:
```bash
#!/bin/bash
for i in {1..10}
do
echo "Creating child process $i"
(sleep 1; echo "Child process $i (pid $$) exiting") &
done
wait
echo "All child processes have exited"
```
这个脚本使用 for 循环创建 10 个子进程。每个子进程会在输出自己的 pid 后等待 1 秒钟,然后退出。wait 命令会等待所有子进程结束后再退出。
可以将上述代码保存为一个可执行脚本文件,比如 test.sh,然后在终端中执行以下命令来运行:
```
$ chmod +x test.sh
$ ./test.sh
```
这个脚本会输出类似下面的内容:
```
Creating child process 1
Creating child process 2
Creating child process 3
Creating child process 4
Creating child process 5
Creating child process 6
Creating child process 7
Creating child process 8
Creating child process 9
Creating child process 10
Child process 1 (pid 1234) exiting
Child process 2 (pid 1235) exiting
Child process 3 (pid 1236) exiting
Child process 4 (pid 1237) exiting
Child process 5 (pid 1238) exiting
Child process 6 (pid 1239) exiting
Child process 7 (pid 1240) exiting
Child process 8 (pid 1241) exiting
Child process 9 (pid 1242) exiting
Child process 10 (pid 1243) exiting
All child processes have exited
```
阅读全文