Linux NASM检测EOF [英] Linux NASM detect EOF
问题描述
我正在尝试学习Linux上的asm基础知识,但找不到很好的参考资料.NASM文档似乎假设您已经知道masm ......我没有在 cmp
(在Intel指令参考之外)的文档中找到任何示例.
I'm trying to learn the basics asm on linux and I can't find a very good reference. The NASM docs seem to assume you already know masm... I found no examples in the documentation of the cmp
(outside the Intel instruction reference).
我编写了一个程序,该程序从stdin读取一个字节并将其写入stdout.下面是我的修改,以尝试在stdin上检测EOF并在达到EOF时退出.问题是它永远不会退出.我只是继续打印从stdin读取的最后一个字符.问题是我检测到EOF( cmp ecx,EOF
)和/或我跳到 _exit
标签( je _exit
)
I'd written a program that reads a single byte from stdin and writes it to stdout. Below is my modification to try to detect EOF on stdin and exit when EOF is reached. The issue is it never exits. I just keeps printing the last char read from stdin. The issue is either in my EOF detection (cmp ecx, EOF
) and/or my jump to the _exit
label (je _exit
) I think.
我在做什么错了?
%define EOF -1
section .bss
char: resb 1
section .text
global _start
_exit:
mov eax, 1 ; exit
mov ebx, 0 ; exit status
int 80h
_start:
mov eax, 3 ; sys_read
mov ebx, 0 ; stdin
mov ecx, char ; buffer
cmp ecx, EOF ; EOF?
je _exit
mov edx, 1 ; read byte count
int 80h
mov eax, 4 ; sys_write
mov ebx, 1 ; stdout
mov ecx, char ; buffer
mov edx, 1 ; write byte count
int 80h
jmp _start
出于理智,我确认此C的EOF为-1:
For the sake of sanity, I verified EOF is -1 with this C:
#include <stdio.h>
int main() { printf("%d\n", EOF); }
推荐答案
您正在将缓冲区的地址与EOF(-1)(而不是存储在缓冲区中的字符)进行比较.
You are comparing the address of the buffer to EOF (-1) instead of the character stored in the buffer.
话虽如此, read
系统调用在到达文件末尾时不会返回EOF的值,但是会返回零且不会在缓冲区中粘贴任何内容(请参见男人2阅读
).要识别文件结尾,只需在调用 read
后检查 eax
的值:
Having said that, the read
system call does not return the value of EOF when end of file is reached, but it returns zero and doesn't stick anything in the buffer (see man 2 read
). To identify end of file, just check the value of eax
after the call to read
:
section .bss
buf: resb 1
section .text
global _start
_exit:
mov eax, 1 ; exit
mov ebx, 0 ; exit status
int 80h
_start:
mov eax, 3 ; sys_read
mov ebx, 0 ; stdin
mov ecx, buf ; buffer
mov edx, 1 ; read byte count
int 80h
cmp eax, 0
je _exit
mov eax, 4 ; sys_write
mov ebx, 1 ; stdout
mov ecx, buf ; buffer
mov edx, 1 ; write byte count
int 80h
jmp _start
如果您确实想将字符正确地与某个值进行比较,请使用:
If you did want to properly compare the character to some value, use:
cmp byte [buf], VALUE
此外,我将 char
重命名为 buf
. char
是基本的C数据类型,并且是变量名的错误选择.
Also, I renamed char
to buf
. char
is a basic C data type and a bad choice for a variable name.
这篇关于Linux NASM检测EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!