clinuxpipenamed-pipesmkfifo

Writing and reading named pipes


I want to write and read from pipes . I have written a code in C it is compiled successfully but when i run it by ./write it has runtime error . Here are my read and write codes.

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>

int main(void) {
    int fd, retval;
    char buffer[] = "TESTDATAAA";
    
    fflush(stdin);
    retval = mkfifo("/temp/myfifo",0666);
    fd = open("/temp/myfifo",O_WRONLY);
    write(fd,buffer,sizeof(buffer));
    close(fd);
    return 0;
}
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>

int main() {
    int fd, retval;
    char buffer[] = "TESTDATA";
    
    fd = open("/temp/myfifo",O_RDONLY);
    retval = read(fd, buffer, sizeof(buffer));
    fflush(stdin);
    write(1, buffer, sizeof(buffer));
    printf("\n");   
    close(fd);
    return 0;
}

Any help will be appreciated.


Solution

  • "doing nothing" is very different than "has runtime error". If you run ./write and the program blocks, that is expected behavior. The fopen will not return until some other process has opened the fifo for reading.

    Open a second terminal and execute your consumer while the producer is running.