为什么这个汇编代码不再重复读取相同的字节,而是返回和文件结束?

时间:2015-01-13 16:30:42

标签: linux assembly x86 nasm eof

这是我的代码:

section .bss
    bufflen equ 1024
    buff: resb bufflen

    whatread: resb 8

section .data

section .text

global main

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic

                            ; Eax currently has the return value from linux system call..
        add eax, 30h        ; Convert number to ASCII digit
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        mov ecx,whatread    ; Get the address of whatread in ecx
        mov edx,4           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic

                            ; Eax currently has the return value from linux system call..
        add eax, 30h        ; Convert number to ASCII digit
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        mov ecx,whatread    ; Get the address of whatread in ecx
        mov edx,4           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

    mov eax, 1; 
    mov ebx, 0; 
    int 80h

我有一个名为 all.txt 的文件,内容为:

61 62 63 0A 64 65 66 0A (abc - new line - def - new line)

以下是一个示例运行:

koray@koray-VirtualBox:~/asm/buffasm$ ./buff < all.txt
80koray@koray-VirtualBox:~/asm/buffasm$ 

因此,第一次读取代码会尝试从文件中读取1024个字节。文件本身有8个字节..然后它在控制台打印8,我猜是好的。但是,为什么它打印'0'表示文件结束?我希望它再次读取相同的8个字节?为什么要尝试读取下一个1024字节?

1 个答案:

答案 0 :(得分:0)

程序没有逻辑再次读取相同的字节。它们已经被读取并且在缓冲区中。输入缓冲区(由重定向文件填充)为空,因此无法读取更多字节。这就是sys_read以0读取字节结束的原因。

如果它不是STDIN,那么同样的逻辑将是一个真实的文件(当然,之前由sys_open打开)。

顺便说一句,返回0的数字实际上就是所谓的EOF。