I an trying to create a program in c that has one parent process and three child ones. The aim is that the parent will be connected with each child with two pipes so when the children choose to send a message to one of their siblings they will send it first to the parent and then it will send it to the appropriate child. The read ends of the parent have to be non-blocking .
I have tried to follow the example that is in the https://www.geeksforgeeks.org/non-blocking-io-with-pipes-in-c/ site . The two errors that I have are the following: 1)array type has incomplete element type ‘int[]’ void parent_read(int pipes[][]) (line 11)
2)type of formal parameter is incomplete parent_read(pipes); (line140)
What can I do to fix it? And is what I have done till now in regards to non-blocking correct?
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <time.h>
#define MSGSIZE 5
void parent_read(int pipes[][])
{
int nread;
char buf[MSGSIZE];
// write link
close(pipes[1]);
while (1) {
// read call if return -1 then pipe is
// empty because of fcntl
nread = read(pipes[0], buf, MSGSIZE);
switch (nread) {
case -1:
// case -1 means pipe is empty and errono
// set EAGAIN
if (errno == EAGAIN) {
printf("(pipe empty)n");
sleep(1);
break;
}
else {
perror("read");
exit(4);
}
// case 0 means all bytes are read and EOF(end of conv.)
case 0:
printf("End of conversationn");
// read link
close(pipes[0]);
exit(0);
default:
// text read
// by default return no. of bytes
// which read call read at that time
printf("MSG = %sn", buf);
}
}
}
int main()
{
int pids[3],id[3];
int pipes[6][2];
int i;
for (i=0;i<6;i++)
{
if (pipe(pipes[i])==-1)
{
printf("Error in pipe: %dn",i);
return 0;
}
else
{
printf("Error in pipe:!n");
}
}
if (fcntl(pipes[0][0], F_SETFL, O_NONBLOCK) < 0)
{
exit(2);
}
for(i=0;i<3;i++)
{
pids[i]=fork();
if(pids[i]==0)
{
id[i]=getpid();
//printf("ID:%dn",id[i]);
break;
}
}
if (getpid()==id[0])
{
for (i=0;i<6;i++)
{
if (i>0 && i>1)
{
close(pipes[i][0]);
close(pipes[i][1]);
printf("Pipes of A have closed:%dn",i);
}
}
/* char* x="hello";
if (write(pipes[1][1],&x,sizeof(int)) == -1)
{
printf("error in write");
}*/
return 0;
}
if (getpid()==id[1])
{
for (i=0;i<6;i++)
{
if ((i>2 && i>3) || (i<2 && i<3))
{
close(pipes[i][0]);
close(pipes[i][1]);
printf("Pipes of B have closed:%dn",i);
}
}
return 0;
}
if (getpid()==id[2])
{
for (i=0;i<6;i++)
{
if (i<4 && i<5)
{
close(pipes[i][0]);
close(pipes[i][1]);
printf("Pipes of C have closed:%dn",i);
}
}
return 0;
}
if(getpid()!=0)
{
// char y;
parent_read(pipes); //Here i try to call parent read
//read(pipes[1][0],&y,sizeof(int));
//printf("The child processe has given:%y",y);
for(i=0;i<=3;i++)
{
wait(NULL);
}
printf("PARENT:%dn",getpid());
}
}
Niko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.