简体   繁体   English

终端自动输入来自程序的输入作为命令

[英]Terminal automatically entering input from program as a command

I am trying to teach myself how to write Assembly in X86 on NASM.我正在尝试自学如何在 NASM 上的 X86 中编写程序集。 I'm attempting to write a program that takes a single integer value and prints it back to standard output before exiting.我正在尝试编写一个程序,该程序采用单个整数值并在退出之前将其打印回标准输出。

My code:我的代码:

section .data
        prompt: db "Enter a number: ", 0
        str_length: equ $ - prompt

section .bss
        the_number: resw 1

section .text

global _start

_start:
        mov eax, 4      ; pass sys_write
        mov ebx, 1      ; pass stdout
        mov edx, str_length     ; pass number of bytes for prompt
        mov ecx, prompt     ; pass prompt string
        int 80h
        
        mov eax, 3      ; sys_read
        mov ebx, 0      ; stdin
        mov edx, 1      ; number of bytes
        mov ecx, [the_number]       ; pass input of the_number
        int 80h
        
        mov eax, 4
        mov ebx, 1
        mov edx, 1
        mov ecx, [the_number]
        int 80h
        
        mov eax, 1          ; exit
        mov ebx, 0          ; status 0
        int 80h

From there I do the assembling nasm -felf -o input.o input.asm and linking ld -m elf_i386 -o input input.o .从那里我组装nasm -felf -o input.o input.asm并链接ld -m elf_i386 -o input input.o

I run a test and input an integer and when I press enter, the program exits and Bash tries to execute the number input as a command.我运行一个测试并输入一个整数,当我按 Enter 时,程序退出,Bash 尝试将输入的数字作为命令执行。 I even echo 'd the exit status and been returned with 0.我什至echo了退出状态并返回了 0。

So this is an odd behavior.所以这是一个奇怪的行为。

The call to read fails and doesn't read any input.读取调用失败并且不读取任何输入。 When your program exits, that input is still waiting to be read on the TTY (which was this program's stdin), at which point bash reads it.当您的程序退出时,该输入仍在等待在 TTY(这是该程序的标准输入)上读取,此时 bash 读取它。

You should check the return status of your system calls.您应该检查系统调用的返回状态。 If EAX is a negative number when the system call returns, it is the error code.如果系统调用返回时 EAX 为负数,则为错误代码。 For example, in this case, EAX contains -14, which is EFAULT (“Bad address”).例如,在这种情况下,EAX 包含 -14,即 EFAULT(“错误地址”)。

The reason read fails is that you are passing an invalid pointer as the buffer address.读取失败的原因是您将无效指针作为缓冲区地址传递。 You need to load the address of the_number , not its value.您需要加载the_number的地址,而不是它的值。 Use mov ecx, the_number .使用mov ecx, the_number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM