file - C - Create/Write/Read named pipe -


i want create named pipe , write , after want read it. here code:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <fcntl.h> #define fifo "fifo0001" int main(intargc, char *argv[]){     char input[256];     file *fp;     char str[50];     printf("please write text:\n");     scanf("%s", input);     unlink(fifo); /* because exists, unlink before */     umask(0);     if(mkfifo(fifo, 0666) == -1){         printf("something went wrong");         return exit_failure;     }     if((fp = fopen(fifo, "a")) == null){         printf("something went wrong");         return exit_failure;     }     fprintf(fp, "%s", input);     if(fgets(str, 50, fp) != null){         puts(str);     }     fclose(fp);     return exit_success; } 

after write text, nothing happen anymore. , there no message. have quit program strg c. know wrong? have use functions mkfifo, fopen, fprintf, fgets , fclose. nice if keep them code.

fifo's don't work nice 1 thread. you'll blocked on reading open until writing open performed , vice versa, you'll need open in rdwr mode or blocked.

e.g.:

fp = fopen(fifo, "r+"); 

then you'll need write no more size of fifo buffer (which ulimit -p * 512 ?) (or else blocked). after that, you'll need read no more you've written.

all in all, should work (although it's not usual way use fifos):

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <fcntl.h> #define fifo "fifo0001"  int main(int argc, char *argv[]){     char input[256] = "hw";     file *fp;     char str[50];     printf("please write text:\n");     scanf("%s", input); //!!!      size_t input_len = strlen(input);      unlink(fifo); /* because exists, unlink before */     umask(0);     if(mkfifo(fifo, 0666) == -1){         printf("something went wrong");         return exit_failure;     }     if((fp = fopen(fifo, "r+")) == null){         printf("something went wrong");         return exit_failure;     }     fprintf(fp, "%s", input);     if(fgets(str, input_len+1, fp) != null){         puts(str);     }     fclose(fp);     return exit_success; } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -