how to use "popen" or "pipe" for sending one c programme output to another c programme input

My aim is to communication of two processes through popen.
Here my two process are matrix_sum.c (for addition of two matrices)and display_format.c(display formatting)

Just below is my main programme(programme by popen).
In Main.c i am trying to read matrix_sum.c output that i able to read through popen in buffer. Then i am trying to send that output to display_format.c programme but it is not going. So it is not printing any thing.
Note:display_format and matrix_sum are my executable file corresponding to .c file

Main.c...................
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main()
{
FILE *read_fp;
FILE *write_fp;
char buffer[BUFSIZ + 1];
int chars_read;
int read,i;
memset(buffer, '\0', sizeof(buffer));
read_fp = popen("./matrix_sum", "r");
chars_read = fread(buffer,sizeof(char),BUFSIZ,read_fp);
pclose(read_fp);
write_fp = popen("./display_format", "w");
fwrite(buffer, sizeof(char), strlen(buffer), write_fp);
pclose(write_fp);
printf("\n");
return 0;
}

matrix_sum.c......................................
#include<stdio.h>

int main(){
int a[123][123];
int b[123][123];
int c[123][123];
int i,j;
a[0][0]=1;
a[0][1]=2;
a[1][0]=1;
a[1][1]=2;
b[0][0]=2;
b[0][1]=1;
b[1][0]=2;
b[1][1]=1;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(" %d",c[i][j]);
}
}
return 0;
}

display_format.c...................................................
#include<stdio.h>
int main(int argc,char *argv[]){
int i,j,k=1;
int c[123][123];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=atoi(argv[k]);
k++;
}
}

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

return 0;
}

Please any one correct this simple programme
such that matrix_sum out put goes to display_format via popen
Thank You
Last edited on
First, you need to check for errors when functions return -- especially popen(). It may return NULL, and because your code doesn't check for it, your program will crash in the case it returns NULL.

Your display_format program doesn't read standard-in, which is where your main program is writing.

Have you tried running the programs by themselves to see if they work?
Topic archived. No new replies allowed.