Multiplying 2D arrays using fork()

HI,
i am trying to multiply 2 2D arrays (a[2][3],b[3][4]) using fork.
The answer will be at c[2][4].
Each child have to calculate 1 row of c[2][4].
The code is right, as i think of it, with no errors but i dont get the correct c array...
I think there is maybe a mistake in i dimension ...
Anyway, here is the code:

//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row

#include<stdio.h>
#include<stdlib.h>

main()
{
  int a[2][3]={1,2,3, 
	       4,5,6};
  int b[3][4]={1,2,3,4,
	       5,6,7,8,
	       9,10,11,12};
  int c[2][4];
  int i,j;
  int m;	//for the calculation
  int n;	//common 3
  int pid;	//fork
  
  for(i=0;i<2;i++)
  {
    pid=fork();
    if(pid==-1)
    {
      printf("Can't fork\n");
    }
    if(pid==0)//child
    {
      for(j=0;j<4;j++)
      {
	for(n=0;n<3;n++)
	{
	  m=m+a[n]*b[n][j];
	}
	c[j]=m;
	m=0;
      }
      exit(EXIT_SUCCESS);
    }
    if(pid>0)//parent
    {
      wait(0);
    }
  }
  printf("C:\n");
  for(i=0;i<2;i++)
  {
    for(j=0;j<4;j++)
    {
      printf("%d\t",c[j]);
    }
    printf("\n");
  }	       
}

Any help, please ?

First, move your initialisation of m to the start of the loop:

for(j=0;j<4;j++)
{    
    m = 0;
    for(n=0;n<3;n++)
    {
        m=m+a[n]*b[n][j];
    }   
    c[j]=m;
}
  

That would only affect your [0][0] value though.

The reason you're not seeing the result you expect is that you're not passing back the computed value from the child to the parent. With fork(), the child receives a copy of the process, but any manipulations to the data segment are local to the child. If you memset() your result array to -99 or something, you'll notice that it's still -99 at the end.

To pass back values from the child, have a look at creating a pipe that the child can write to and the parent can read from. See the man(2) page for pipe which will have all the details that you'll need.

Are you expecting child processes storing numbers in their copy of array c to update array c in the parent?

I didnt knew that child processes use a copy of the variables i use. i should re-check the man fork(). Yes i want to update array c in the parent. Looking pipes ...

---------- Post updated at 07:01 PM ---------- Previous update was at 07:00 PM ----------

Initiliazation corrected. Just looking for the use of pipes...

---------- Post updated at 08:40 PM ---------- Previous update was at 07:01 PM ----------

Ok, i read about pipe.
Trying to figure out how it works, i made an easy example.
The program makes a multiply of 2 integers (a and b) and saves the answer to c...

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

main()
{
  int a,b,c;
  int pid;
  int pipefd[2];
  char buff[10];
  char str[100+1]={'\0'};
  int w,r;
  a=3;
  b=10;
  
  pipe(pipefd);
    if(pipefd<0)
      printf("pipe error\n");
    
  pid=fork();
  if(pid==-1)
    printf("Fork error\n");
  if(pid==0)
  {
    //child
    c=a*b;
    printf("child says answer %d\n",c);
    
    sprintf(str,"%d",c);
    w=write(pipefd[1],str,c);
    if(w!=c)
      printf("write error");
    exit(0);
  }
  if(pid>0)
  {
    //parent
    printf("father says answer %d\n",c);
    wait(0);
    
    r=read(pipefd[0], buff, sizeof(buff));
    if(r<=0)
      printf("read error\n");
    c=atoi(buff);
    printf("child told father answer is %d\n",c);
    
  } 
}

It works with no errors or notifications... :rolleyes:
But when i tried with the arrays, troubles appeared again...
Any help?
Based on my first code and adding pipes i have this :

//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

main()
{
  int a[2][3]={1,2,3, 
	       4,5,6};
  int b[3][4]={1,2,3,4,
	       5,6,7,8,
	       9,10,11,12};
  int c[2][4];
  int i,j;
  int m[4];	//for the calculation. Array is just an idea, dont know if works
  int n;	//common 3
  int pid;	//fork
  int pipefd[2];
  int w,r;    //for write() and read()
  char buff[100];
  char str[100+1]={'\0'};
   
  for(i=0;i<2;i++)
  {
    pipe(pipefd);
      if(pipefd<0)
	printf("Pipe error\n");
    pid=fork();
    if(pid==-1)
    {
      printf("Can't fork\n");
    }
    if(pid==0)//child
    {
      for(j=0;j<4;j++)
      {
	//m initialize
	for(n=0;n<3;n++)
	{
	  m[j]=m[j]+a[n]*b[n][j];
	}
      }
      //what !?
      sprintf(str,"%d",m[j]);
      w=write(pipefd[1],"%d",m);
      if(w!=m)
	printf("write error\n");
      //m=0;
      exit(0);
    }
    if(pid>0)//parent
    {
      wait(0);
      r=read(pipefd[0], buff,sizeof(buff));
      if(r<=0)
	printf("read error\n");
    }
  }
  printf("C:\n");
  for(i=0;i<2;i++)
  {
    for(j=0;j<4;j++)
    {
      printf("%d\t",c[j]);
    }
    printf("\n");
  }	       
}

Of course, it doesnt works. Its unfinished. But i want help...
I will update it when i change something...

Only have time for a quick look, but this is what jumped out at me:

Write is not like printf(), it takes a buffer of data and a length and doesn't do any formatting. You had the right idea in your first test (without arrays), but you need to give write the length -- you gave it 'c' which probably caused write to grab too many bytes depending on the value of c.

data_len = snprintf( str, sizeof( str ), "%d\n", m[j]);
write( pipe[1], str, data_len );

I added a new line -- you'll need some form of space between the data that the parent process will be reading.

Hope this gets you a bit further.

There are many things wrong with the pipe and array code...not initalizing m[4] to 0 before using it in the addition and in the parent you are not reading the value into c[i][j] but instead putting it into buff.

Looking for it and will reply back!
Thanks :b:

I'm trying to correct the code. i have this now:

//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

main()
{
  int a[2][3]={1,2,3, 
	       4,5,6};
  int b[3][4]={1,2,3,4,
	       5,6,7,8,
	       9,10,11,12};
  int c[2][4];
  int i,j;
  int m[4];	//for the calculation
  int n;	//common 3
  int pid;	//fork
  int pipefd[2];
  int w,r;
  char buff[100];
  char str[100+1]={'\0'};
  int data_len;
  int temp;
   
  for(i=0;i<2;i++)
  {
    pipe(pipefd);
      if(pipefd<0)
	printf("Pipe error\n");
    pid=fork();
    if(pid==-1)
    {
      printf("Can't fork\n");
    }
    if(pid==0)//child
    {
      for(j=0;j<4;j++)
      {
	for(n=0;n<3;n++){m[n]=0;}	//initialize m[4]
	for(n=0;n<3;n++)
	{
	  m[j]=m[j]+a[n]*b[n][j];
	}
      }
      for(j=0;j<4;j++)
      {
	sprintf(str,"%d",m[j]);
	w=write(pipefd[1],str,data_len);
      }
      exit(0);
    }
    if(pid>0)//parent
    {
      wait(0);
      for(i=0;i<4;i++)
      {
	m=read(pipefd[0], buff, sizeof(buff));
      }
    }
    
  }
  printf("C:\n");
  for(i=0;i<2;i++)
  {
    for(j=0;j<4;j++)
    {
      printf("%d\t",c[j]);
    }
    printf("\n");
  }	       
}

i'm confused about how to put the m array in each column of c...
By the way i get no compilng errors, but the program dont run...
I cant understand the use of snprintf() :wall:

I've made changes to your code, and have a working copy. I'll post my comments so if you want to work the changes yourself you can; I can post the code if you'd rather me do that.

In no real order:

Your initialisation and loop to compute m[] in the child runs from i=0; i < 3 which isn't initialising m[3], nor computing the value for m[3].

The initialisation of m[] must go before for(j=0;j<4;j++) otherwise you reset the values of m to zero before you are ready to write them to the parent.

you should close the reading side of the pipe in the child before you start (good ptractice), and you should close the writing end before the child exits.

You should close the writing end of the pipe in the parent before calling wait(); again good practice.

When writing your results to str in prep to send to parent, you need to add a space to the value, "%d " , so that the values are delimited when the parent reads them.

You should write a final end of string to the parent, and you should close the writing side of the pipe before the child exits.

In the parent:

            for(i=0;i<4;i++)
            {
                m=read(pipefd[0], buff, sizeof(buff));
            }

This just won't work. The read will read everything that the child has written on the first read -- provided that the buffer is large enough, and for this small sample programme it is. Just because the child wrote 4 times (+ one end of string write), doesn't mean that the parent will need to read 5 times. Also, you're assigning the return code from the read() and not the value to m[i], You need to do one read, check for error, and then use sscanf() to parse the buffer and fill in c[i][j].

The parent should close the reading end of the pipe before looping.

I think those were all of the changes I needed to make to get your code to work. Post back if you want me to post the actual code -- Not sure if you want the experience of figuring it out, or want to see the example, and will error on the side of letting you work through it.

I look your comments and tried to adjust my program. I think i correct these :

The code is now :

//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

main()
{
  int a[2][3]={1,2,3, 
	       4,5,6};
  int b[3][4]={1,2,3,4,
	       5,6,7,8,
	       9,10,11,12};
  int c[2][4];
  int i,j;
  int m[4];	//for the calculation
  int n;	//common 3
  int pid;	//fork
  int pipefd[2];
  int w,r;
  char buff[100];
  char str[100+1]={'\0'};
  int temp;
   
  for(i=0;i<2;i++)
  {
    pipe(pipefd);
      if(pipefd<0)
	printf("Pipe error\n");
    pid=fork();
    if(pid==-1)
    {
      printf("Can't fork\n");
    }
    if(pid==0)//child
    {
      for(n=0;n<3;n++){m[n]=0;}	//initialize m[4]
      for(j=0;j<4;j++)
      {
	for(n=0;n<3;n++)
	{
	  temp=temp+a[n]*b[n][j];
	}
	m[j]=temp;
	sprintf(str,"%d ",m[j]);
	w=write(pipefd[1],str,sizeof(str));
	if(w!=sizeof(str))
	  printf("\nWrite error");
      }
      exit(0);
    }
    if(pid>0)//parent
    {
      wait(0);
      r=read(pipefd[0], buff, sizeof(buff));
      if(r<=0)
	printf("\nRead Error");
      for(n=0;n<3;n++)
      {
	sscanf(m[n],"%s",buff);	//or otherwise
	c[n]=m[n];	//give to c each time a row
      }
    }
    
  }
  printf("C:\n");
  for(i=0;i<2;i++)
  {
    for(j=0;j<4;j++)
    {
      printf("%d\t",c[j]);
    }
    printf("\n");
  }	       
}

I get a notice in sscanf in compiling :

example.c: In function �main�:
example.c:61:2: warning: passing argument 1 of �sscanf� makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:450:12: note: expected �const char * __restrict__� but argument is of type �int�

and a Segmentation fault as an output.
So i'm working on pipes, to fix the other issues...
I want to learn how to use the pipes, thanks for your time and explanations. I will try more and if i give up, i'll tell you to send me the final code to study and work on it. Thanks!

See my comments in red above...it needs more fixes but that is left as an exercise for the op...

Because your parent process waits for the child to exit, all data will be read into the buffer, and you'll need to pull all of the values out in a single sscanf() call.

Something like this:

          if( (data_len = read( pipefd[0], buff, sizeof( buff )  )) <= 0 )            /* mimimal error checking, get data from child */
          {
                fprintf( stderr, "read failed: %s\n", strerror( errno ) );
                exit( 1 );
          }

            sscanf( buff, "%d %d %d %d", &c[0], &c[1], &c[2], &c[3] );      /* scan the buffer, convert each to int and place in m */

You'll also notice that the buffer that sscanf() is to read is the first parameter, followed by the format string, and then pointer(s) to the locations that are to be populated. In your case, you can populate all 4 with one scanf() call.

First of all thanks for the help you giving to me.
I am new in programming. Actually i am studying in informatics. That's also the reason my code is a mess, i mean lining and everything ...
I tried to fix it...

//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

main()
{
	int a[2][3] = {1,2,3, 
	       	       4,5,6};
  	int b[3][4] = {1,2,3,4,
	       	       5,6,7,8,
	       	       9,10,11,12};
  	int c[2][4] = { 0 };
  	int i, j;
  	int n;	//common 3
  	int pid;
  	int pipefd[2];
  	int w, data_len;
  	char buff[100];
  	char str[100+1] = {'\0'};
   
  	for ( i=0;i<2;i++ )
  	{
    		pipe(pipefd);
      		if( pipefd < 0 )
			printf("Pipe error\n");
    		pid = fork();
    		if( pid == -1 )
    		{
      			printf("Can't fork\n");
    		}
    		if( pid == 0 )//child
    		{
      			for( j=0;j<4;j++ )
      			{
				for( n=0;n<3;n++ )
				{
	  				c[j] += a[n]*b[n][j];
        			}
        			sprintf( str, "%d ", c[j] );
        			w = write( pipefd[1], str, sizeof (str) );
        			if( w != sizeof (str) )
	    				printf("\nWrite error");
			}
      			exit(0);
    		}
    		if( pid > 0 )//parent
    		{
      			wait(0);
      			if( ( data_len = read( pipefd[0], buff, sizeof ( buff ) ) ) <=0 )
      			{
				fprintf( stderr,"Read failed: %d\n", strerror( errno ) );	//%s gives me a warning so i checked man errno and 
				exit(1);							//change it to %d
      			}
			sscanf( buff, "%d %d %d %d", &c[0], &c[1], &c[2], &c[3]);
    		}
  	}
  	printf("C:\n");
  	for( i=0;i<2;i++ )
  	{
    		for( j=0;j<4;j++ )
    		{
      			printf("%d\t",c[j]);
    		}
    		printf("\n");
  	}	       
}

Almost done!
I get no Segmentation fault, no errors or warnings in compiling!
But C array has the right numbers only in c[0][0] and c[1][0], at others i get 0s.
So its like this:

C:
38	0	0	0	
83	0	0	0

Tryin' to fix that ...

Great progress!

You need to correct a few things if you haven't.

First, the warning about %s in conjunction with strerror() is because you haven't included string.h. The strerror() function returns a pointer to a string, and if you don't include string.h the compiler assumes that it returns int, and thus issues the warning about the mismatch with %s. Include string.h and change the %d to a %s. It has nothing to do with the type of errno .

You also should include sys/types.h and sys/wait.h.

Your initialisation of a, b and c is missing curly braces. To be correct, you need something like this for a and b:

int a[2][3] = { {1,2,3},
                   {4,5,6} };

For c you need

int c[2][4] = { {0}, {0} };

Those are all to correct compiler warnings. The real problem is in your writing from the child. You are converting each value to string and placing it in str with a terminating NULL character. That is correct. However, you are writing the entire buffer, including the characters past the NULL to the parent. You need to write just the values, and the associated trailing blank, to the parent. To do this you need to capture the length of the string created by sprintf() and use that as the number of characters to write to the pipe. For completeness, I would also write a final NULL to the pipe after all of the values. Something like the code segment below:


                    len = sprintf( str, "%d ", c[j] );   // length of value+blank into len
                    w = write( pipefd[1], str, len  );     // write only the value and blank
                    if( w != len )                         // check the number written, not the size of str
                        printf("\nWrite error");        // maybe exit too?
            }
            *str = 0;                     // write a final NULL to terminate the string
            write( pipefd[1], str, 1 );
            exit(0);

Yes, the way you changed it works perfectly thanks!
But, i will connect this code with another part which read the arrays from a .txt file.
I have already done the reading part, but i think that this part :

if( pid > 0 )//parent
    		{
      			wait(0);
      			if( ( read( pipefd[0], buff, sizeof ( buff ) ) ) <=0 )
      			{
				fprintf( stderr,"Read failed: %s\n", strerror( errno ) ); 
				exit(1);
      			}
			sscanf( buff, "%d %d %d %d", &c[0], &c[1], &c[2], &c[3]);
    		}

will be a problem because is "manual". Is there a way i can use this part for different types of arrays. For example if my c wasnt with 4 columns. I am thinking something like puting the sscanf() into a for(), but my tries dont work....

No, you cannot just place it into a loop because there is no way to 'mark' the buffer and start sscanf where it left off. You can do something like this:

#include <string.h>
#include <unistd.h>
#include <stdio.h>

void read_row( int fd, int *m, int cols )
{
    char    *tok;
    int     j;
    char    *place;         /* strtok place holder */
    char    buf[2048];

    if( read( fd, buf, sizeof( buf ) ) <= 0 )   /* we assume buffer is null terminated by writer */
        return;                                 /* needs more error checking */


    tok = strtok_r( buf, " ", &place );
    for( j = 0; tok  &&  j < cols; j++ )
    {
        m[j] = atoi( tok );
        tok = strtok_r( NULL, " ", &place );
    }

}

int main( )
{

    int a[3][10];  /* should initialise */
    int i;
    int j;

    read_row( 0, a[0], 10 );   /* read three rows of 10 digits each into matrix */
    read_row( 0, a[1], 10 );
    read_row( 0, a[2], 10 );

    for( i = 0; i < 3; i++ )
    {
        printf( "[ " );
        for( j = 0; j < 10; j++ )
            printf( "%d ", a[j] );
        printf( "]\n" );
    }
}

I've included a complete (though lacking in error checking etc.) programme should you want to play with it a bit. It reads three records, each with 10 digits, from stdin and puts them into the rows. I think that you need just the part in bold to process the buffer that is read from the pipe.

Thanks for your example!
I didnt understand a lot at the beginning, but then i looked for strtok_r() more at the manual and finally i got what i wanted.
Sorry for the late answer, and thanks for your time! :b: