64位Ubuntu下汇编I/O教程:基础输入功能实现咨询
Basic Input Functionality in x64 Assembly (64-bit Ubuntu)
Nice work getting the basic output sorted for your x64 assembly tutorial on 64-bit Ubuntu! Let's walk through adding basic input functionality using Linux system calls—this follows a similar pattern to your existing output code, just with the sys_read system call instead.
First, a quick breakdown of how sys_read works for x86_64 Linux:
- The system call number for
sys_readis 0, so we load that intorax rditakes the file descriptor: use 0 for standard input (stdin)rsiholds the memory address of the buffer where we'll store the inputrdxsets the maximum number of bytes to read (make sure your buffer is large enough for expected input!)
Here's a complete, working example that reads user input, then prints it back to the terminal to verify it worked:
global _start section .text _start: ; Step 1: Read input from standard input mov rax, 0 ; syscall number for sys_read mov rdi, 0 ; file descriptor 0 = stdin mov rsi, buffer ; pointer to our input buffer mov rdx, 256 ; max bytes to read (matches buffer size) syscall ; trigger the system call ; After sys_read returns, rax holds the number of bytes actually read ; We can reuse this value to print exactly what the user entered ; Step 2: Print the input back to standard output mov rdx, rax ; use the byte count from sys_read mov rax, 1 ; syscall number for sys_write mov rdi, 1 ; file descriptor 1 = stdout mov rsi, buffer ; same buffer containing the user's input syscall ; trigger the system call ; Step 3: Exit the program gracefully mov rax, 60 ; syscall number for sys_exit xor rdi, rdi ; exit code 0 (success) syscall section .bss buffer resb 256 ; Reserve 256 bytes of uninitialized memory for input
Key Details to Explain in Your Tutorial:
- We use the
.bsssection for the buffer instead of.databecause it's uninitialized memory—this is better practice for buffers since we don't need pre-set values.resb 256tells the assembler to reserve 256 bytes of space. - After
sys_readruns,raxstores how many bytes were actually read (including the newline character if the user pressed Enter). We use this value insys_writeto avoid printing unused buffer space. - The exit logic is identical to your original output program—cleanly exiting with a success code.
Compilation & Run Steps:
- Save the code as
input.asm - Assemble with NASM:
nasm -f elf64 input.asm -o input.o - Link with the linker:
ld input.o -o input - Run the program:
./input
When you run it, type some text and press Enter—you'll see your input printed right back!
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

