简体   繁体   中英

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.

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM