How to make multiple interacting fork () `-eded processes using shared memory?

I have a parent with 5 child processes. I want to send a random variable to each child process. Each child will square the variable and send it back to the parent, and the parent sums them all together.

Is it possible? I can't figure it out ...

edit: this process will use shared memory.

+3
source share
3 answers

There are many ways to do this, all of which are associated with some form of interprocess communication. Which one you choose will depend on many factors, but some of them:

  • shared memory.
  • pipe (popen ..).
  • .

, , , popen ; , .

, , , , :

  • .
  • (0 = start, 1 = , 2 = ).

, , , . , PID . , , 1, PID - PID.

:

  • . , PID .
  • Main "start".
  • Main , .
  • Main PID.
  • = " " PID.
  • Main (state = "ready for child", PID = pid1, value = 7).
  • Main (state = "ready for child", PID = pid5, value = 9).
  • pid1 , 49, " " ), .
  • pid5 , 81, "ready for parent" ), .
  • Main pid5, , .
  • Main pid1, , .

parallelism, , , .

+6

vfork() ; .

, , , vfork() .

() :

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/wait.h>

int main(void)
{
    int i;
    int array[5];
    int square[5];
    long sum = 0;

    srand(time(0));
    for (i = 0; i < 5; i++)
    {
        array[i] = rand();
        if (vfork() == 0)
        {
            square[i] = array[i] * array[i];
            execl("/bin/true", "/bin/true", (char *)0);
        }
        else
            wait(0);
    }

    for (i = 0; i < 5; i++)
    {
        printf("in: %d; square: %d\n", array[i], square[i]);
        sum += square[i];
    }
    printf("Sum: %d\n", sum);
    return(0);
}

. , 'exit(0)' 'execl()', ; . (32- Solaris 10, SPARC):

in: 22209; square: 493239681
in: 27082; square: 733434724
in: 2558; square: 6543364
in: 17465; square: 305026225
in: 6610; square: 43692100
Sum: 1581936094

- .

Solaris vfork() :

fork(),    execve() ( ,  _exit() (. exit (2)). ,     vfork().   , .

, , , "wait()" . ( , , . , i , wait() , . _exit() execl() , , . vfork(), , - .)

+3

Things like anti-thread can make this a little easier for you, see examples (particularly the ns search program).

0
source

Source: https://habr.com/ru/post/1703939/


All Articles