2015-11-08 67 views
1

我已经创建了fifo,尝试写入它:echo "text" > myfifo 并用我的程序读取它。 但是当我写信给fifo什么都没有显示。在Linux下编程 - 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]); 
} 
+2

您使用了'C++'标签,但是这看起来是直接的C代码。 –

+0

反正它不起作用... – Knight

+1

你到底在干什么?怎么了?你预期会发生什么? – melpomene

回答

0

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

必须

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

(有可能是没有必要的O_NONBLOCK标志,但你的最严重的错误是,你要指定一个布尔结果( 0或1;不是文件描述符)至tab[i]

最后但并非最不重要的是,对于

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

工作,你需要把一个空字符你读的最后一个字符之后:

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

(你也需要确保始终有一个为终止空空间:要么要求9字符或为数组分配11)。

+0

非常感谢,像魅力:) – Knight