user11432153
user11432153

Reputation:

Using named pipes in c

i have this simple program that passes a value through a named pipe from child to parent process:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
 #include <sys/wait.h>
 #include <stdio.h>

int main()
{
 char * myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd,rec;
   pid_t c=fork();

   if(c==0){
   fd = open(myfifo, O_WRONLY);
   rec=100;
   write(fd, rec, sizeof(rec));

   }
   if(c>0){
   sleep(1);
    fd = open(myfifo, O_RDONLY);
     read(fd, rec, sizeof(rec));
     printf("%d\n",fd);
     printf("%d\n",rec);

   }

}

This program prints fd=-1 and instead of rec being 100 it prints rec's address.I also tried putting &rec in read and write but it did not solve anything.What am i doing wrong?

Upvotes: 1

Views: 248

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15576

There's an issue with this line:

write(fd, rec, sizeof(rec));

This is the prototype of write():

ssize_t write(int fd, const void *buf, size_t count);

That means that you're reading from the memory location stored in rec, not the content of rec.

The same thing applies for read(). You need to pass a pointer to rec instead of rec itself.

Also, always make sure to close files after you open and perform I/O on them.

Here's a correct copy of your code:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>

int main()
{
   const char *myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd, rec;
   pid_t c = fork();

   if(c == 0) {
       fd = open(myfifo, O_WRONLY);
       rec = 100;
       write(fd, &rec, sizeof(rec));
       close(fd);
   }
   if(c > 0) {
       sleep(1);
       fd = open(myfifo, O_RDONLY);
       read(fd, &rec, sizeof(rec));
       printf("%d\n", fd);
       printf("%d\n", rec);
       close(fd);
   }
}

Of course, always make sure you have the proper permissions to create, read, and write files in that directory. Also, make sure the directory /home/tmp exists.

Upvotes: 3

Related Questions