C - 创建/写入/读取命名管道

时间:2016-05-28 18:48:10

标签: c file pipe fopen fifo

我想创建一个命名管道,然后写入它,之后我想读它。这是我的代码:

#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 some text:\n");
    scanf("%s", input);
    unlink(FIFO); /* Because it already exists, unlink it 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;
}

写完文字后,再也没有发生了什么。而且没有消息。我必须退出STRG C的程序。有人知道出了什么问题吗?我必须使用函数mkfifo,fopen,fprintf,fgets和fclose。如果我能将它们保留在代码中,那就太好了。

1 个答案:

答案 0 :(得分:1)

FIFO只用一个线程就不好用了。 您将在读取打开时被阻止,直到执行写入打开,反之亦然,因此您需要在RDWR模式下打开或者您被阻止。

E.g:

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

然后你需要写入不超过FIFO缓冲区的大小(ulimit -p * 512?)(否则你被阻止)。在那之后,你不需要阅读你所写的内容。

总而言之,这应该有用(虽然这不是使用FIFO的常用方法):

#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 some text:\n");
    scanf("%s", input); //!!!

    size_t input_len = strlen(input);

    unlink(FIFO); /* Because it already exists, unlink it 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;
}
相关问题