I need to build a process tree using fork()in C. I get a sequence of numbers from standard input (for example: 1 5 0 3), and these numbers tell me how many of them each have a node. If we take an example, then the root process will create 1 child, then this one child will create 5 of their own children, and then of these 5 children, the first will not create any children, the second will create 3 of them, made. Upon completion of this process, the root process calls pstreewhich draws the tree.
Here is an example image:

My question is: how can I create new children from a specific node? You need to create 0 new processes, and the next you need to create 3 of them. I do not know how to distinguish so that only this particular child creates new children, and not all of them. Also, I'm not sure how to use it pstree, because the tree, as a rule, has already disappeared when called pstree. I know that I can wait()have the children do the former, but the latter do not have children to wait, so they end too quickly.
I wrote code that creates an example. We need ideas on how to generalize this to different materials. Also can someone show me how to call pstree from this code, because I cannot get it to work.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
pid_t temppid;
pid_t temppid2;
int root_pid;
int status;
root_pid = getpid();
pid = fork();
if (pid == 0) {
pid = fork();
if (pid != 0) {
temppid = getpid();
if (getpid() == temppid) {
pid = fork();
if (pid == 0) {
temppid2 = getpid();
if (getpid() == temppid2) {
fork();
}
if (getpid() == temppid2) {
fork();
}
if (getpid() == temppid2) {
fork();
}
}
}
if (getpid() == temppid) {
fork();
}
if (getpid() == temppid) {
fork();
}
if (getpid() == temppid) {
fork();
}
}
}
else {
pid = fork();
if (pid == 0) {
}
}
while (1) {
sleep(1);
}
}
source
share