hkn
hkn

Reputation: 371

passing 2D Array to recursion

I am trying to make calculations with using fork in C. I have a 2D array with members {1,2,3,4}, I have a function to get square for each member in the array. I will call this function with child processes. For example for 3 child process output will be like this;

1.Child
1 4
9 16
----------
2.Child
1 16
81 256
----------
3.Child
1 256
6561 65536

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

int matrix[2][2] = {1, 2, 3 ,4 }  ;

int main(){
forkFork(3);
}

void forkFork(int counter)
{
    pid_t pid;
    if(counter == 0)
    {
        exit(0);
    }
    if(counter > 0)
    {
        if ((pid = fork()) < 0)
        {
            perror("fork error :(");
        }
        else if (pid == 0)
        {
            matrixPower(matrix);
            print(matrix);
        }
        else if(pid > 0)
        {
            forkFork(counter - 1);
        }
    }
}

void matrixPower(int m[2][2])
{
    int i,j,k;
    int result = 0;

    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            result =  matrix[i][j]*matrix[i][j];

            m[i][j] = result;
            result = 0;
        }
    }
}

void print(int a[2][2])
{
    int row, col ;
    for(  row = 0; row < 2; row++ )
    {
        for(  col = 0; col < 2 ; col++ )
        {
            printf("%d\t", a[row][col]);
        }
        puts("");
    }

        printf("-------------------------------\n");
}

I could not find a way to pass new array to recursion function...

Upvotes: 1

Views: 695

Answers (1)

hmatar
hmatar

Reputation: 2419

The problem with your solution is that all forked processes are created by the main/parent process. Therefore, each forked process just inherits the address space of the parent whose matrix values are always {1, 2, 3, 4}. The solution is for each modifying process to create its child process. Thus a new child process inherits the modified matrix.

See my solution below for forkFork function which works as expected.

void forkFork(int counter)
{
    pid_t pid;
    if(counter == 0)
    {
        exit(0);
    }
    if(counter > 0)
    {
        if ((pid = fork()) < 0)
        {
            perror("fork error :(");
        }
        else if (pid == 0)
        {
            matrixPower(matrix);
            print(matrix);
            forkFork(counter - 1);
        }
    }
}

Upvotes: 1

Related Questions