【发布时间】:2022-01-13 23:29:47
【问题描述】:
每个人。
我正在学习操作系统课程,我的任务是使用 fork 用 C 语言编写以下进程树。程序必须接收 2 个参数,即高度和宽度(分别为 3 和 2)并创建此图像的树:
在图像上,P.I = Parent Process ,Hijo N= N Child Process,Nieto N = N Grandson 和 Bisnieto N = N Great Grandson。
代码必须使用以下模板:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i, height, width;
if (argc!= 3) exit(0);
height = atoi(argv[1]); /* height */
width = atoi(argv[2]); /* width */
/* Your code goes here */
printf("I am the process %d and my father is %d\n", getpid(),
getppid());
sleep(1);
return 0;
}
我做了几个代码,但我找不到解决方案,我最接近的是下一个代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int
main (int argc, char *argv[])
{
int i,x, height, width;
pid_t pid,pid2;
if (argc != 3)
exit (0);
height = atoi (argv[1]); /* height */
width = atoi (argv[2]); /* width */
/* Your code goes here */
for (i = 1; i < height; i++)
{
pid=fork();
if(pid<0){pid2 = fork();}
}
printf ("I am the process %d and my father is %d\n", getpid (), getppid ());
sleep (1);
return 0;
}
但是唯一缺少的就是创建第一个进程(P.I)的两个子进程,hijo 2=child 2 of the diagram is not created.
我还尝试创建一个代码,一个接一个地创建一个进程链,另一个代码从一个父进程创建两个进程,但我不知道如何加入代码来创建这棵树。有人可以帮我吗?
这是我制作的链的代码:
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int i, height, width;
pid_t pid,pid2;
if (argc!= 3) exit(0);
height = atoi(argv[1]); /* height */
width = atoi(argv[2]);
for (int i=0; i<height; i++)
{
pid = fork();
if (pid == -1) { /* handle error*/ }
else if (pid == 0) {
printf("Soc el process %d y meu pare es %d\n", getpid(),getppid());
}
else { // parent process
wait(NULL);
exit(0);
}
}
printf("Soc el process %d y meu pare es %d\n", getpid(),getppid());
}
我创建的创建一个父母的两个孩子的代码是这个:
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int i, height, width;
pid_t pid,pid2;
if (argc!= 3) exit(0);
height = atoi(argv[1]); /* height */
width = atoi(argv[2]); /* width */
/* tu codigo aqui */
for(int i=0;i<width;i++) // loop will run n times (n=5)
{
if(fork() == 0)
{
printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
printf("Soc el process %d y meu pare es %d\n", getpid(),getppid());
for(int i=0;i<height;i++) // loop will run n times (n=5)
wait(NULL);
}
我想知道加入两个代码或修改第一个代码是否更好,以及如何做到:C
【问题讨论】:
-
我投票结束这个问题,因为在家庭作业上寻求帮助需要帖子就特定问题提出特定问题。
标签: c for-loop process fork binary-tree