Reputation: 6689
I have two simple programs that use named pipes, here is the first:
int main(int argc,char **argv)
{
if (argc<2)
error_nsys_f("usage: [fifo]");
if (mkfifo(argv[1],S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)<0)
error_sys_f("error while creating named pipe");
int fd=open(argv[1],O_RDONLY);
int log_file=open("wyniki.log",O_WRONLY | O_CREAT| O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
long result;
size_t len;
if (fd<0)
error_sys_f("error while openning pipe");
if (log_file<0)
error_sys_f("error while openning log file");
//unlink(argv[1]);
char path[MAXLINE];
char buffer[BUF];
while(1)
{
if (read(fd,&len,sizeof(size_t)) == -1)
{
cleanup(fd,argv[1]);
error_sys_f("error while reading from file-name queue");
}
if (read(fd,path,len) == -1)
{
cleanup(fd,argv[1]);
error_sys_f("error while reading from file-name queue");
}
result=count(path,buffer);
if (result>-1)
{
sprintf(buffer,"%s: %ld\n",path,result);
if (write(log_file,buffer,strlen(buffer)) == -1)
{
cleanup(fd,argv[1]);
error_sys_f("error while writing to log-file");
}
}
}
}
and the second one
int main(int argc,char **argv)
{
if (argc<3)
error_nsys_f("usage: [fifo] [plik1] [plik2]...\n");
int fd=open(argv[1],O_WRONLY);
int i;
int s;
if (fd<1)
error_sys_f("nie udalo sie otrzymac dostepu do kolejki");
for(i=2;i<argc;++i)
{
s=strlen(argv[i])+1;
if (write(fd,&s,sizeof(size_t)) == -1)
{
close(fd);
error_sys_f("error while writing to queue");
}
if (write(fd,argv[i],strlen(argv[i])+1) == -1)
{
close(fd);
error_sys_f("error while writing to queue");
}
}
close(fd);
return EXIT_SUCCESS;
}
in the second program I give him the name of the fifo to write to and names of the files, in the first one I read the length of name and file-name, count the bytes and write it to log-file.
But there is a problem, if I try to write for example one file name to the fifo, the first program reads the name and the length ok, preforms the counting but after that he reads the same file-name all the time from fifo. He behaves like he didn't remove the message read from fifo. What is the cause of this?
Upvotes: 0
Views: 2434
Reputation: 229058
You are not handling the case where read() returns 0 , which means there is no more data and the other end has closed the pipe.
So your code should stop looping if read() returns 0 as well, not just when it returns -1
Upvotes: 3