【发布时间】:2011-10-07 04:17:32
【问题描述】:
显然是家庭作业,但我不是要求任何人为我做,而是我只是想要方向。到目前为止,我已经把它写成一个 fork 进程树(这很难弄清楚)
/* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include<errno.h>
int main()
{
pid_t leftchild;
pid_t rightchild;
pid_t pid;
int level=0;
int max;
printf("Enter in max level for process tree: ");
scanf(" %d", &max);
pid=getpid();
fprintf(stderr,"I am the parent process with and id of: %ld\n", (long)getpid());
for(; level<max; level++){
leftchild=fork();
if (leftchild == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
if(leftchild==0){
fprintf(stderr,"Level is %d, i am %ld , my parent is %ld\n",level, (long)getpid(), (long)getppid());
continue;
}
else{
rightchild=fork();
if(rightchild==0){
fprintf(stderr,"Level is %d, i am %ld , my parent is %ld\n",level, (long)getpid(), (long)getppid());
continue;
}
}
wait(NULL);
wait(NULL);
break;
}
}
这个程序创建了这棵树
i
/\
i i
/\ /\
i i i i
我需要创建另一个具有这样的树的叉树:
i
/ \
i i
/\
i i
/\
i i
/\
i i
我应该考虑对我的程序进行哪些修改?
我尝试在 rightchild if 语句中创建另一个分支,但没有成功。我什至尝试将所有内容分开,但失败得很惨。我只是没有从逻辑上看到解决方案。有什么提示或建议吗?
我尝试过递归:
/* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include<errno.h>
pid_t leftchild;
pid_t rightchild;
pid_t pid;
int level=0;
int max;
void recurse(){
if(level<2){
leftchild= fork();
if (leftchild == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
if(leftchild==0){
fprintf(stderr,"Level is %d, i am %ld , my parent is %ld\n",level, (long)getpid(), (long)getppid());
}
rightchild=fork();
if (rightchild == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
}
if(rightchild==0){
fprintf(stderr,"Level is %d, i am %ld , my parent is %ld\n",level, (long)getpid(), (long)getppid());
}
level++;
recurse();
}
}
int main()
{
printf("Enter in max level for process tree: ");
scanf(" %d", &max);
pid=getpid();
fprintf(stderr,"I am the parent process with and id of: %ld\n", (long)getpid());
recurse();
}
这实际上不会因为任何原因返回 pid,有什么特别的原因吗?
【问题讨论】:
-
我太n00b无法标记帖子;但是,如果您想添加“家庭作业”标签,那就太好了。