myfifo并用我的程序阅读它。但是当我写入 fifo 时,什么也没有显示。 我尝试了很多选项,关闭和打开 NON_BLOCK 模式等等,但-6ren">
gpt4 book ai didi

c - Linux 编程 - 先进先出

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:45 26 4
gpt4 key购买 nike

我已经创建了 fifo,尝试写入:echo "text"> myfifo并用我的程序阅读它。但是当我写入 fifo 时,什么也没有显示。

我尝试了很多选项,关闭和打开 NON_BLOCK 模式等等,但似乎没有任何帮助。

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

int main (int argc, char **argv)
{

int c;

int tab[argc/2];//decriptors
int i=0;
while ((c = getopt (argc, argv, "f:")) != -1) {
switch (c) {
case 'f':
if (tab[i] = open(optarg, O_RDONLY| O_NONBLOCK) == -1) {
perror(optarg);
abort();
}
//dup(tab[i]);
//printf(":::::%d==== %s\n",555,optarg);
i++;
break;

default:
abort();
}
}
printf("----------------------\n");

char cTab[10];
int charsRead;
for(int j=0;j<=i;j++)
{
charsRead = read(tab[j], cTab, 10);

printf(" ==%d+++%s\n",tab[j],cTab);
//write(tab[j],cTab,10);
}
for(int j=0;j<i;j++)

{
close(tab[j]);
}

最佳答案

这个

      if (tab[i] = open(optarg, O_RDONLY| O_NONBLOCK) == -1) {

需要

      if ((tab[i] = open(optarg, O_RDONLY)) == -1) {

(可能不需要 O_NONBLOCK 标志,但您最严重的错误是您将 bool 结果(0 或 1;不是文件描述符)分配给 tab[i] )

最后但同样重要的是,对于

  printf(" ==%d+++%s\n",tab[j],cTab);

要工作,您需要在读取的最后一个字符后放置一个空字符:

  if(charsRead >= 0) 
cTab[charsRead] = 0;

(您还需要确保终止空值始终有空间:要求 9 个字符或为数组分配 11 个字符)。

关于c - Linux 编程 - 先进先出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596146/

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