如何创建unix进程二叉树?
有人可以帮我一下吗,不一定能完成我的作业。
我需要使用 fork() 创建一个进程树;到目前为止,在 Unix/C 中,我能达到的最好的第四级是我的代码:
/* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
int main()
{
pid_t childpid;
pid_t pid;
int i;
childpid=fork();
waitpid();
i=0;
for (; i<1; i++) {
int b=0;
for (; b<1;b++) {
childpid=fork();
fprintf(stderr,"the value of i is %d, i am %ld , my parent is %ld\n",
i, (long)getpid(), (long)getppid());
if (childpid==0) {
break;
}
}
if (childpid==0) {
break;
}
}
sleep(1);
}
我对 C 编程非常陌生,总体上编程很好,所以我想问一下公众我缺少哪些步骤。树深度需要由用户指定,所以我想我会使用 na for 循环,但这只会在一个级别上相乘,而不是创建新级别。
有人可以帮助我并指出我正确的方向吗:) 我需要它像这样分叉
i
/ \
/ \
/ \
/ \
/ \
i i
/ \ / \
/ \ / \
i i i i
/ \ / \ / \ / \
i i i i i i i i
Can some one help me out here, not necessarily complete my homework.
I need to create a process tree using fork(); in Unix/C so far the best I can get to to the 4th level here is my code:
/* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
int main()
{
pid_t childpid;
pid_t pid;
int i;
childpid=fork();
waitpid();
i=0;
for (; i<1; i++) {
int b=0;
for (; b<1;b++) {
childpid=fork();
fprintf(stderr,"the value of i is %d, i am %ld , my parent is %ld\n",
i, (long)getpid(), (long)getppid());
if (childpid==0) {
break;
}
}
if (childpid==0) {
break;
}
}
sleep(1);
}
I am very new to C programming, well programming in general, so I wanted to ask the general public what steps I am missing. The tree depth needs to be user specified so I figured I would use n a for loop but that only multiplies across a level rather than creating new levels.
Can someone help me out and point me in the right direction :)
I need it to fork like this
i
/ \
/ \
/ \
/ \
/ \
i i
/ \ / \
/ \ / \
i i i i
/ \ / \ / \ / \
i i i i i i i i
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
waitpid()
函数需要参数。最初的
childpid = fork();
是意外的。您可以明智地编写:
for 循环,除非您坚持使用 C89 而不是 C99 语法。
尝试 2
示例输出
示例源
这使用了一个循环,一个有点不寻常的循环。在每个级别,父进程分叉两个子进程;子级各自“继续”到下一个级别,而父级则完成并退出循环。清理代码与之前相同(见下文)。
递归变体
尝试 1
我不相信您需要任何循环。这似乎对我有用:
示例输出
源代码
The
waitpid()
function requires arguments.The initial
childpid = fork();
is unexpected.You can sensibly write:
for the loops unless you insist on using C89 instead of C99 syntax.
Attempt 2
Example output
Example source
This uses a loop, a somewhat unusual loop. At each level, the parent process forks two children; the children each 'continue' to the next level, while the parent is done and exits the loop. The clean up code is the same as before (see below).
Recursive variant
Attempt 1
I'm not convinced you need any loops. This seemed to do the trick for me:
Example output
Source Code