【问题标题】:Read/Write FIFO in TCL and C, garbage outputTCL 和 C 中的读/写 FIFO,垃圾输出
【发布时间】:2014-02-11 15:01:27
【问题描述】:

我正在尝试在 TCL 脚本和 C 代码之间建立连接。

这是 TCL 脚本

set fs[open "./fifo_server" "w"]
puts $fs "level_3"
flush $fs

这里是 C 代码

if ((fs = fopen ("./fifo_server", "r"))== NULL)
    perror ("error occured while opening FIFO_SERVER");
  else {
    fs1 = fileno(fs);
    read(fs1, in_data, sizeof(in_data));
  }
  printf ("in_data = %s\n", in_data);

输出如下:

in_data = level_3
(some garbage stuff 5 spaces which contains Question marks, Squares, 
Characters etc.)

我不明白,垃圾线可能是什么原因???

感谢您的准确和早期帮助。

感谢和问候, M.

【问题讨论】:

  • 一次性使用set fs [open "./fifo_server" "w"]。空间在 Tcl 中很重要。
  • 您为什么使用filenoread 而不是fread?或者,相反,fopen 而不是open?尽量避免对一个文件描述符/句柄使用两个 API……
  • @Jerry 我认为这一定是一个转录错误,否则代码永远不会像报告的那样有效。

标签: c tcl readfile fifo


【解决方案1】:

首先,正如 Jerry 所指出的,您需要在变量 fs 和方括号之间留一个空格:

set fs [open "./fifo_server" "w"]

我不知道您以这种低级方式读取文件的原因(即使用文件编号,而不是 FILE* 句柄)。但是,您需要自己终止字符串,因为 read() 不会自动这样做:

int chars_read; /* How many chars read from a file */

if ((fs = fopen ("./fifo_server", "r")) == NULL)
    perror ("error occured while opening FIFO_SERVER");
else {
    fs1 = fileno(fs);
    chars_read = read(fs1, in_data, sizeof(in_data));
    in_data[chars_read] = '\0'; /* terminate your string */
}
printf ("in_data = %s\n", in_data);

【讨论】:

  • 这对我来说似乎是个问题,因为所有预期的字节也都在之前垃圾。经典的溢出症状。
  • 我不认为这是一个超限问题。 read()fread() 旨在读取原始数据。这样,它们就不会 NULL 终止您的缓冲区。
  • 否;溢出发生在printf(),因为数据未终止。这根本不是read() 的错,它正在做它记录的事情。
最近更新 更多