[英]Linux NASM detect EOF
I'm trying to learn the basics asm on linux and I can't find a very good reference. 我正在尝试在linux上学习基础知识,我找不到一个很好的参考。 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). NASM文档似乎假设您已经知道masm ...我在
cmp
的文档中找不到任何示例(在Intel指令参考之外)。
I'd written a program that reads a single byte from stdin and writes it to stdout. 我编写了一个从stdin读取单个字节并将其写入stdout的程序。 Below is my modification to try to detect EOF on stdin and exit when EOF is reached.
下面是我的修改,尝试在stdin上检测EOF并在达到EOF时退出。 The issue is it never exits.
问题是它永远不会退出。 I just keeps printing the last char read from stdin.
我只是继续打印从stdin读取的最后一个char。 The issue is either in my EOF detection (
cmp ecx, EOF
) and/or my jump to the _exit
label ( je _exit
) I think. 问题出在我的EOF检测(
cmp ecx, EOF
)和/或我想跳转到_exit
标签( je _exit
)。
What am I doing wrong? 我究竟做错了什么?
%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
For the sake of sanity, I verified EOF is -1 with this C: 为了理智,我用这个C验证EOF是-1:
#include <stdio.h>
int main() { printf("%d\n", EOF); }
You are comparing the address of the buffer to EOF (-1) instead of the character stored in the buffer. 您正在将缓冲区的地址与EOF(-1)进行比较,而不是存储在缓冲区中的字符。
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
). 话虽如此,当达到文件结尾时,
read
系统调用不返回EOF的值,但它返回零并且不会在缓冲区中粘贴任何内容(参见man 2 read
)。 To identify end of file, just check the value of eax
after the call to read
: 要识别文件结尾,只需在调用
read
之后检查eax
的值:
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
Also, I renamed char
to buf
. 另外,我将
char
重命名为buf
。 char
is a basic C data type and a bad choice for a variable name. char
是基本的C数据类型,是变量名称的错误选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.