PDA

View Full Version : FIFO "connections"



np2k
06-08-2010, 06:44 AM
I've this code and a client that send data on the FIFO.
I start the client and the daemon below works perfectly. But when the client stop beacause of while cycle we go to "read function" and now (after the termination of the client) there is no wait for an another client and the read function reads the last structure.
what's the problem?



#define FIFO_PATH "/home/np2k/Desktop/fifo.txt"

struct data {
int channel;
int pid;
};

int main()
{
int fd;
int fifod;
printf("daemon> started...\n");
if (mkfifo(FIFO_PATH,S_IWUSR|S_IRUSR) == -1)
{
perror("mkfifo");
exit(1);
}
if ( (fd = open(FIFO_PATH,O_RDONLY)) == -1)
{
perror("open");
exit(1);
}

while(1)
{
struct data getdata;

printf("daemon> waiting for connection...\n"); fflush(NULL);
if (read(fd,&getdata,sizeof(struct data)) == -1)
{
printf("***************************\n");
perror("read");
exit(1);
}

printf("daemon> connection ok...\n");
printf("daemon> channel: %d, pid: %d\n",getdata.channel,getdata.pid);

char fifo_name[100];
char buf;
sprintf(fifo_name, "%d", getdata.pid);

strcat(fifo_name,"OK");
printf("daemon> fifo name: %s\n",fifo_name);

if (mkfifo(fifo_name,S_IWUSR|S_IRUSR) == -1)
{
perror("mkfifo");
exit(1);
}
if ( (fifod = open(fifo_name,O_RDONLY)) == -1)
{
perror("open");
exit(1);
}

printf("daemon> WAITING....\n"); fflush(NULL);
read(fifod,&buf,1);
printf("daemon>>>>>>>>>%c\n",buf); fflush(NULL);
if (buf == 's')
{
printf("daemon> start ok\n");
close(fifod);
}
}

close(fd);

return 0;
}

itCbitC
06-14-2010, 07:44 PM
For starters, why do you create a new fifo everytime instead of resuing the original one "/home/np2k/Desktop/fifo.txt"? And what is fflush(NULL)?

laserlight
06-15-2010, 04:15 AM
And what is fflush(NULL)?
Flush all open output streams.

itCbitC
06-15-2010, 09:54 AM
Flush all open output streams.
Cool beans!
I wasn't sure if that was correct but you and the manpage cleared it up.