assembly - sys_nanosleep 禁止光标在终端中移动
问题描述
我正在使用系统调用和基本的 c stdlib 在 Linux 的 x86-64 程序集中制作蛇游戏。我做了一个函数来设置终端中的光标位置,在等待 1 秒后,在游戏循环的每次迭代中调用该位置(1 秒用于调试,在实际游戏中更少)。如果我不睡觉,光标会成功移动,但如果我这样做,它不会。这是我的代码:
global main
extern putc
extern printf
extern fflush
%define MAP_WIDTH 20
%define MAP_HEIGHT 20
%define MAP_COUNT (MAP_WIDTH * MAP_HEIGHT)
%define SCREEN_WIDTH (MAP_WIDTH + 1)
%define SCREEN_HEIGHT MAP_HEIGHT
%define SCREEN_COUNT (SCREEN_WIDTH * SCREEN_HEIGHT)
%define WAIT_TIME_NS (150 * 10^6)
%define MAX_SNAKE_LENGTH MAP_COUNT
section .text
; Functions: rdi, rsi, rdx, rcx, r8, r9
; Syscalls: rax, rdi, rsi, rdx
clear_console:
mov rax, 1 ; RAX: Syscall #1 : Write
mov rdi, 1 ; RDI: File Handle #1 : Stdout
mov rdx, CLEAR_CMD_LEN ; RDX: Length
mov rsi, CLEAR_CMD ; RSI: char*
syscall ; Perform the syscall
ret
sleep_before_next_iteration:
mov rax, 35 ; RAX: Syscall #35: sys_nanosleep
mov rdi, SLEEP_TIMESPEC ; RDI: req: pointer to struct timespec.
xor rsi, rsi ; RSI: mem: struct timespec* (NULL here)
syscall ; Perform the syscall
ret
exit_program:
mov rax, 60 ; RAX: Syscall #60: Exit
xor rdi, rdi ; RDI: Error Code 0: Clean Exit
syscall ; Call Syscall
ret
go_to_location: ; Args (rdi: x, rsi: y)
; Move Cursor To Position
mov rdx, rsi ; Argument 2; %d for y
mov rsi, rdi ; Argument 1: %d for x
mov rdi, MOVE_CURSOR_CMD ; Argument 0: string to format
call printf
ret
main:
call clear_console
game_loop_iterate:
call sleep_before_next_iteration
; Print Apple
mov rdi, 5 ; goto x
mov rsi, 7 ; goto y
call go_to_location
mov rax, 1 ; RAX: Syscall #1 : Write
mov rdi, 1 ; RDI: File Handle #1 : Stdout
mov rdx, 1 ; RDX: Length
mov rsi, APPLE_STR ; RSI: char*
syscall ; Perform the syscall
jmp game_loop_iterate
game_loop_end:
call exit_program
ret
section .data:
SLEEP_TIMESPEC: dq 1, 0
APPLE_STR: db "apple string", 0
MOVE_CURSOR_CMD: db 0x1B, "[%d;%df", 0
CLEAR_CMD: db 27,"[H",27,"[2J" ; Clear Console Command
CLEAR_CMD_LEN: equ $-CLEAR_CMD ; Length Of The Clear Console Command
任何帮助将非常感激!我认为这不是sys_nanosleep
这个问题的根本原因,因为它只是在睡觉,但我一直在寻找大约半天。
信息:
- 内核:5.4.0-42-generic
- 操作系统:Ubuntu 20.04 LTS
建造:
nasm -felf64 -g ./snake.asm
clang snake.o -o snake
谢谢!
解决方案
推荐阅读
- ruby-on-rails - 接受属性的字符串输入,将整数存储在数据库中,在 API 中返回字符串
- amazon-web-services - 使用 Terraform 旋转具有一定有效性的 AWS EC2 Spot 实例
- html - 如何构建所有具有相同宽度的 DIV 的响应式网格
- reactjs - 如何处理 setState 是异步的?
- assembly - 如何计算 MIPS ASSEMBLY 中标签的地址?
- javascript - Quasar Cordova 谷歌地图插件
- javascript - 找到点之间的路径。迷宫算法太慢
- mysql - SQL合并不同的表数据计数
- javascript - 如何将base13字符串转换为base64
- javascript - 如何解决 UnhandledPromiseRejectionWarning: ValidationError?