gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:25 25 4
gpt4 key购买 nike

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

#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。如果我能将它们保留在代码中,那就太好了。

最佳答案

FIFO 不能只使用一个线程。您将在读取打开时被阻塞,直到执行写入打开,反之亦然,因此您需要在 RDWR(非可移植)模式下打开,或者在一个线程中使用 RDONLY,在另一个线程中使用 WRONLY,否则您将被阻塞.

例如:

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;
}

关于C - 创建/写入/读取命名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37502683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com