簡體   English   中英

nasm 程序集 linux 計時器或睡眠

[英]nasm assembly linux timer or sleep

我試圖找到一種方法讓我的代碼在繼續之前等待兩秒鍾。 我在保護模式下為 Linux 使用 nasm,所以我只能使用 int 80h。 我發現了一個名為“ alarm ”(27)的syscall調用和另一個名為“ pause ”(29)的syscall調用。 但是,當我嘗試使用它們時,程序會等待並完成而不是繼續執行。 我還發現了另一個syscall sigaction,它改變了信號的行為(所以我認為它可以用來使程序忽略警報生成的信號而不是退出),但我不太明白 sigaction 是如何工作的。 謝謝你的幫助。 有用的鏈接: http : //man7.org/linux/man-pages/man2/alarm.2.html http://man7.org/linux/man-pages/man2/sigaction.2.html

有一個用於休眠程序的系統調用sys_nanosleep

 sys_nanosleep : eax = 162, ebx = struct timespec *, ecx = struct timespec *

這個struct timespec結構有兩個成員:

 ;; This is for 32-bit.  Note that x86-64 uses 2x 64-bit members
tv_sec   ; 32 bit seconds
tv_nsec  ; 32 bit nanoseconds

這個結構可以在 nasm 中聲明為:

section .data

  timeval:
    tv_sec  dd 0
    tv_usec dd 0

然后設置值並將其稱為:

mov dword [tv_sec], 5
mov dword [tv_usec], 0
mov eax, 162
mov ebx, timeval
mov ecx, 0
int 0x80

然后程序將休眠 5 秒鍾。 一個完整的例子:

global  _start

section .text
_start:

  ; print "Sleep"
  mov eax, 4
  mov ebx, 1
  mov ecx, bmessage
  mov edx, bmessagel
  int 0x80

  ; Sleep for 5 seconds and 0 nanoseconds
  mov dword [tv_sec], 5
  mov dword [tv_usec], 0
  mov eax, 162
  mov ebx, timeval
  mov ecx, 0
  int 0x80

  ; print "Continue"
  mov eax, 4
  mov ebx, 1
  mov ecx, emessage
  mov edx, emessagel
  int 0x80

  ; exit
  mov eax, 1
  mov ebx, 0
  int 0x80

section .data

  timeval:
    tv_sec  dd 0
    tv_usec dd 0

  bmessage  db "Sleep", 10, 0
  bmessagel equ $ - bmessage

  emessage  db "Continue", 10, 0
  emessagel equ $ - emessage

使用 NASM,如果您的目標是 Linux x86-64,您可以簡單地執行類似以下操作:

global _start

section .data

    timespec:
        tv_sec  dq 1
        tv_nsec dq 200000000

section .text

    _start:
        mov rax, 35
        mov rdi, timespec
        xor rsi, rsi        
        syscall
        ...

35對應於用於64位系統呼叫號碼sys_nanosleep (所列出這里)。 如果調用中斷,則將剩余的休眠時間寫入寄存器rsi指向的內存位置; 在本例中, rsi設置為 0 以在發生時忽略該值。 此調用將休眠tv_sec seconds + tv_nsec nanoseconds ,在上面的代碼片段中為 1.2 秒。

有關此系統調用的更多信息,請參見nanosleep 手冊頁

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM