Foo*_*ooF 15 linux terminal input
在bash脚本中,我尝试read在设置后使用内置命令从标准输入读取行IFS=$'\n'.如果我将输入粘贴到读取,则会以4095个字符的限制截断这些行.这种限制似乎来自终端阅读,因为这非常好用:
fill=
for i in $(seq 1 94); do fill="${fill}x"; done
for i in $(seq 1 100); do printf "%04d00$fill" $i; done | (read line; echo $line)
Run Code Online (Sandbox Code Playgroud)
我在Python脚本中遇到了相同的行为(不接受来自终端的4095输入,但是从管道接受):
#!/usr/bin/python
from sys import stdin
line = stdin.readline()
print('%s' % line)
Run Code Online (Sandbox Code Playgroud)
即使C程序也是如此,使用read(2):
#include <stdio.h>
#include <unistd.h>
int main(void)
{
char buf[32768];
int sz = read(0, buf, sizeof(buf) - 1);
buf[sz] = '\0';
printf("READ LINE: [%s]\n", buf);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在所有情况下,我输入的时间不能超过4095个字符.输入提示停止接受字符.
问题1:有没有办法以交互方式从Linux系统(至少Ubuntu 10.04和13.04)中读取超过4095个字符的终端?
问题2:此限制来自何处?
受影响的系统:我注意到Ubuntu 10.04/x86和13.04/x86中的这个限制,但是Cygwin(至少是最近的版本)还没有截断超过10000个字符(因为我需要让这个脚本在Ubuntu中运行,所以没有进一步测试).使用的终端:虚拟控制台和KDE konsole(Ubuntu 13.04)和gnome-terminal(Ubuntu 10.04).
Foo*_*ooF 10
请参考termios(3)手册页,"Canonical和noncanonical mode".
默认情况下,终端(标准输入)处于规范模式; 在此模式下,内核将在将输入返回给应用程序之前缓冲输入行.Linux的硬编码限制(可能N_TTY_BUF_SIZE定义为${linux_source_path}/include/linux/tty.h)设置为4096,允许输入4095个字符,不包括结束的新行.在非规范模式下,默认情况下,内核不会进行缓冲,只要返回单个输入字符(按下键),read(2)系统调用就会立即返回.您可以操作终端设置以读取指定数量的字符或为非规范模式设置超时,但是硬编码限制也是4095每个termios(3)手册页.
Bash readbuiltin命令仍然可以在非规范模式下工作,如下所示:
IFS=$'\n' # Allow spaces and other white spaces.
stty -icanon # Disable canonical mode.
read line # Now we can read without inhibitions set by terminal.
stty icanon # Re-enable canonical mode (assuming it was enabled to begin with).
Run Code Online (Sandbox Code Playgroud)
在添加此修改后,stty -icanon您可以粘贴超过4096个字符串并使用bash内置read命令成功读取它(我成功尝试了超过10000个字符).
如果你将它放在一个文件中,即使它成为一个脚本,你可以strace用来查看被调用的系统调用,你会看到read(2)多次调用,每次都返回一个字符.
Sti*_*anE -1
我没有适合您的解决方法,但我可以回答问题 2。在 linux 中,PIPE_BUF 设置为 4096(在 中limits.h)如果您向管道写入超过 4096 的数据,它将被截断。
从/usr/include/linux/limits.h:
#ifndef _LINUX_LIMITS_H
#define _LINUX_LIMITS_H
#define NR_OPEN 1024
#define NGROUPS_MAX 65536 /* supplemental group IDs are available */
#define ARG_MAX 131072 /* # bytes of args + environ for exec() */
#define LINK_MAX 127 /* # links a file may have */
#define MAX_CANON 255 /* size of the canonical input queue */
#define MAX_INPUT 255 /* size of the type-ahead buffer */
#define NAME_MAX 255 /* # chars in a file name */
#define PATH_MAX 4096 /* # chars in a path name including nul */
#define PIPE_BUF 4096 /* # bytes in atomic write to a pipe */
#define XATTR_NAME_MAX 255 /* # chars in an extended attribute name */
#define XATTR_SIZE_MAX 65536 /* size of an extended attribute value (64k) */
#define XATTR_LIST_MAX 65536 /* size of extended attribute namelist (64k) */
#define RTSIG_MAX 32
#endif
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6136 次 |
| 最近记录: |