从NASM中的非阻塞标准输入中读取

问题描述 投票:0回答:1

将stdin设置为非阻塞,然后进行读取系统调用的示例代码。

section .text
    global  _start

_start:
    mov eax,    55           ; __NR_fcntl
    mov ebx,    0
    mov ecx,    4            ; F_SETFL
    mov edx,    2048         ; O_RDONLY|O_NONBLOCK
    int 0x80
    mov eax,    3            ; __NR_read
    mov ebx,    0
    mov ecx,    buf
    mov edx,    1024
    int 0x80
    mov [br],   eax
    mov eax,    4            ; __NR_write
    mov ebx,    1
    mov ecx,    buf
    mov edx,    [br]
    int 0x80
    mov eax,    1            ; __NR_exit
    mov ebx,    0
    int 0x80

section .bss
    buf resb    1024
    br  resd    1

预期的行为:程序退出时不打印任何内容,因为当没有内容可读取时(在终端上),我希望read在EAX中返回0

当前行为:当没有任何内容传递给标准输入时,程序会打印4个随机字节,因为read返回-11。>

$ strace ./nonblocking 
execve("./nonblocking", ["./nonblocking"], 0x7fff196fcb40 /* 53 vars */) = 0
strace: [ Process PID=4112759 runs in 32 bit mode. ]
fcntl(0, F_SETFL, O_RDONLY|O_NONBLOCK)  = 0
read(0, 0x804a000, 1024)                = -1 EAGAIN (Resource temporarily unavailable)
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4294967285����) = 4096
exit(0)                                 = ?

((编者注:\0在终端上打印为零宽度,但问题所涉及的4个非零

字节是-11中的br双字,从输出的1024个字节开始) 。)

将stdin设置为非阻塞,然后进行读取系统调用的示例代码。 .text global _start _start部分:mov eax,55; __NR_fcntl mov ebx,0 mov ecx,4 ...

assembly x86 posix system-calls nonblocking
1个回答
1
投票

Linux系统调用在错误时返回-errno值。 read返回-EAGAIN,该数据在没有字节“就绪”的设备上针对非阻塞I / O进行了记录,因此EAX = -11在其位模式中具有4个非零字节。

您实际上并没有打印4个字节,而是向write传递了一个巨大的值。它一直写到页面末尾

© www.soinside.com 2019 - 2024. All rights reserved.