A
A
alex5e2015-05-26 23:28:16
linux
alex5e, 2015-05-26 23:28:16

How to start several processes in sequence, and pass the exit code of the last child to the first process?

Good evening. Tell me how to complete the task correctly?
It is necessary to create a chain of 5 running processes in sequence, with each child process becoming a parent for the next child. Pass the exit code of the last child to the first process. In the first process, display the given number on the screen.
Created 5 processes in a cycle:

pid_t return_value;

  for(int i = 0; i < 5; i++)
  {
    return_value = fork();
    printf("%s %d %s %d\n", "Процесс: ", getpid(), "PID: ", return_value);	
  }

  return 0;

This code gives me a huge sheet in the terminal,
e2151b60c6034deca6b03100d03ac082.png
I understand that this is due to the fact that after creating a new process, they continue to run in parallel. How to transfer the completion code of the last child to the first process did not figure out. Tell me how to do it right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
werktone, 2015-05-27
@alex5e

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {
    pid_t root_pid = getpid();
    
    for (int i = 0; i < 5; ++i) {
        if (fork() != 0) {
            int status;
            wait(&status);
            int exit_status = WEXITSTATUS(status);
            if (root_pid == getpid()) {
                printf("%d\n", exit_status);
                return 0;
            } else {
                return exit_status;
            }
        }
    }
    return 28;
}

X
xibir, 2015-05-27
@xibir

This code creates not 5, but many more processes. The spawned processes fork further, and those processes turn again until they complete their copy of the cycle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question