doo*_*oku 0 c linux io stdin input
我有一些奇怪的问题.我正在研究一个简单的程序,该程序应该通过网络将从stdin获取的数据发送到该程序的另一个实例,该程序应该将数据直接发送到stdout.但它没有按预期工作,只发送了一部分数据.在那之后,我设法找出了从stdin读取的问题:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 1024
int main(void) {
char *buffer;
int read_bytes;
buffer = (char *) malloc(sizeof(char)*SIZE);
while ((read_bytes = read(STDIN_FILENO,buffer,SIZE)) == SIZE) {
write(STDOUT_FILENO,buffer,SIZE);
fprintf(stderr,"read %d bytes\n",read_bytes);
}
fprintf(stderr,"read %d bytes\n",read_bytes);
write(STDOUT_FILENO,buffer,read_bytes);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(这只是为了简单地说明问题,而不是原始代码的实际部分)
它一切正常( - >将数据从stdin重新发送到stdout),直到我从花费更多时间的东西中获取,例如:
find / | ./the_programme > output.file
Run Code Online (Sandbox Code Playgroud)
输出在几千字节后停止,我真的很困惑为什么(它肯定没有完成).我尝试使用fcntl清除STDIN_FILENO上的O_NONBLOCK标志,但它根本没有帮助.我可能在这里遗漏了一些非常基本的东西,但无论是man page还是google都没有帮助我.
从手册(man 2 read):
返回值:
成功时,返回读取的字节数(零表示文件结束),文件位置按此编号提前.如果此数字小于请求的字节数,则不是错误 ; 这可能发生在例如因为现在实际可用的字节数较少(可能是因为我们接近文件结尾,或者因为我们正在从管道或终端读取),或者因为read()被中断了信号.
while ((read_bytes = read(STDIN_FILENO,buffer,SIZE)) > 0) {
write(STDOUT_FILENO,buffer,read_bytes);
fprintf(stderr,"read %d bytes\n",read_bytes);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2151 次 |
| 最近记录: |