问题描述
我想创建5个进程,就像显示的图片一样,我通过打印出它们的pid尝试了一点点,但是我很难直观地查看创建它们的fork()并得到我想要的[图像显示5个进程通过管道连接]
I want to create 5 processes just like the picture shown i have tried a lil bit by printing out their pid's but its hard for me to visualize the fork() creating them and get exactly what I want [The image shows 5 processes connected by pipes]
P
/ \
M M
| |
C C
推荐答案
当您使用 fork()
时,内核
将创建一个新进程并将其返回给子进程(新过程) 0
和 PID
到父级.因此,知道了这是以下创建树的代码
When you use fork()
the kernel
will create one new process and will return to the child (the new process) 0
and the PID
to the parent. So, knowing this this is the following code to create the tree
if ((pid = fork()) == 0) {
//I am process M1
if (pid = form()) == 0) {
//I am process C1
}
} else {
// I am still in P, so go on the next branch
if ((pid = fork()) == 0) {
//I am process M2
if (pid = form()) == 0) {
//I am process C2
}
}
}
使用 ps --forest
可视化流程树,如以下示例所示
Use ps --forest
to visualize the process tree as in following example
~# ps --forest
PID TTY TIME CMD
1295 pts/0 00:00:00 sudo
1296 pts/0 00:00:00 \_ su
1297 pts/0 00:00:01 \_ bash
3541 pts/0 00:00:00 \_ ps
所以您将看到类似的内容:
So you will see something like:
~# ps --forest
PID TTY TIME CMD
1295 pts/0 00:00:00 a.out
1296 pts/0 00:00:00 \_ a.out
1297 pts/0 00:00:00 \_ a.out
1298 pts/0 00:00:00 \_ a.out
1299 pts/0 00:00:00 \_ a.out
哪位会告诉您您是否成功制作了树.
Which will tell you if you have successfully made the tree.
这篇关于如何使用fork()创建5个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!