c - Read from a pipe(FIFO) then comparing string -
i'm reading pipe.
char buf[255]; while((nbytes = read(fd,buf,sizeof(buf)) > 0)) // fd opened pipe { if(strcmp(buf,"in")==0){ printf("%s\n", "set in"); } if(strcmp(buf,"out")==0){ printf("%s\n", "set out"); } }
now when write pipe via terminal
echo "out" > /path/to/fifo
the output i'm getting is: "set in"
all things type "set in" output. how can compare string read pipe?
you treating read data string (by passing strcmp()
), there no guarantee input data 0-terminated. in particular, read()
doesn't 0-terminate data, fill entire buffer data if possible.
you need yourself, modifying read call like:
while((nbytes = read(fd, buf, sizeof buf - 1)) > 0 ) // fd opened pipe { buf[nbytes - 1] = '\0';
note size passed read()
has shrunk make space terminator, , add it.
also note corrected parentheses in while
, mentioned in comment @ahmedmasud above. that's point, forgot emphasize it.
update: mentioned xaxxon's answer, data delivered in unpredictable chunks, protocol might useful. easiest protocol textual data flowing on pipe (of course?) line-based. mean should collect data until detect end-of-line character. when do, parse contents of buffer, clear it.
Comments
Post a Comment