Question

I'm trying to make a background process named server that uses a named pipe to receive data from a "client" program, and the process saves that data in a file called log. My code is as follows:

server:

main(){

    int fd2,fd_log;
    char *fifo ="/home/me/fifo";
    char c;
    mkfifo(fifo, 0666);
    int x;

   while(fd2 = open(fifo, O_RDONLY)>=0){
      fd_log=open("/home/me/log.txt",O_WRONLY | O_CREAT | O_APPEND);
      while(read(fd2,&c,1)>=0){
          write(fd_log,&c,1);
      }
      close(fd2);
      close(fd_log);
   }
}

client:

main(){

    int fd1;
    char *fifo ="/home/me/fifo";
    char c;

    fd1 = open(fifo, O_WRONLY);
    while(read(0, &c, 1)>=0){
        write(fd1,&c,1);
    }

    close(fd1);
}

However, this doesn't seem to work. There is no action in the log file, and I think the read call in the server file it's not done. Any suggestions?

Was it helpful?

Solution

The problem is in your line here:

while(fd2 = open(fifo, O_RDONLY)>=0){

Due to C operator precedence, this is really evaluated as:

while((fd2 = (open(fifo, O_RDONLY)>=0)) != 0){

I.e. call open(), check if it's return value is greater than 0, then assign that boolean result to fd2, then check if it is zero or not.

That way you are then reading from file no. 1, which is stdout and that surely blocks indefinitely.

Change it to this and everything starts working of course:

while((fd2 = open(fifo, O_RDONLY)) >=0){

Also you are opening the log file without any permissions, you should specify some so that you can access it afterwards somehow, e.g:

fd_log=open("/home/me/log.txt",O_WRONLY | O_CREAT | O_APPEND, 0600);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top