1

I am trying to write a simple program that passes a value from a process to another without having father-child properties using named pipes.Code i've writen:

#include <stdio.h> #include<sys/types.h> #include<unistd.h> #include<stdlib.h> #include<signal.h> int main(int argc, char **argv) { int fd,i,j; int * myfifo = "/tmp/myfifo"; mkfifo(myfifo, 0666); pid_t c=fork(); if(c==0){ i=10; fd = open(myfifo, O_WRONLY); write(fd, &i, sizeof(i)); printf("my pid is %d \n",getpid()); } if(c>0){ pid_t c2=fork(); if(c2==0){ fd = open(myfifo, O_RDONLY); read(fd, &j, sizeof(j)); printf("passes value is %d",j); } wait(0); } } 

I want the first child to write 10 to the pipe and the second to read from the file and print so i can know it works.This code gives me multiple errors though that i can't seen to understand.Any ideas?

Errors i get:

In function ‘main’:| warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]| warning: implicit declaration of function ‘mkfifo’ [-Wimplicit-function-declaration]| warning: implicit declaration of function ‘open’; did you mean ‘popen’? [-Wimplicit-function-declaration]| ]main.c|27|note: each undeclared identifier is reported only once for each function it appears in| error:'O_WRONLY' undeclared(first use in this function) error:'O_RDONLY' undeclared(first use in this function) 
3
  • Which errors do you get? Please attach them to your post. Commented Apr 30, 2019 at 11:02
  • 2
    This code gives me multiple errors ? Please post those error messages in question itself by editing it. Always check the return value of open(). Also do perror on mkfifo to know whether it able to create FIFO or not Commented Apr 30, 2019 at 11:07
  • 2
    See the man page of the implicitly declared functions, e.g. man open and add the missing #include directives. The warning about incompatible types is about myfifo. It must be char * myfifo = "/tmp/myfifo"; (not int *) Check the return value of all functions and print the corresponding error if something fails, e.g. fd = open(...); if(fd < 0) { perror("open"); exit(1); } Commented Apr 30, 2019 at 11:25

1 Answer 1

3

You are not including the proper headers.

For mkfifo() you need sys/stat.h:

SYNOPSIS

#include <sys/stat.h> int mkfifo(const char *path, mode_t mode); 

and for open() you need sys/stat.h and fcntl.h:

SYNOPSIS

[#include <sys/stat.h> #include <fcntl.h> int open(const char *path, int oflag, ...); 

You also need to actually check the return values when you call those functions - the can and do fail.

Sign up to request clarification or add additional context in comments.

2 Comments

...and int * myfifo = "/tmp/myfifo"; is wrong. It must be char *.
@Bodo Thanks. I missed that one.