gpt4 book ai didi

linux - syscall getpid,打印返回值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:52 25 4
gpt4 key购买 nike

我尝试将 getpid 系统调用的结果打印到标准输出。

这是我的汇编代码:

;getpid.asm
[SECTION .txt]
global _start
_start:

xor eax, eax ; clean eax
mov al, 20 ; syscall getpid
int 0x80 ; execute

push eax ; put the return of getpid on the stack
xor eax, eax ; clean
xor ebx,ebx ; clean
xor ecx, ecx ; clean
xor edx, edx ; clean
mov al, 4 ; syscall for write
mov bl, 1 ; stdout 1 in ebx
pop ecx ; put the value returned by getpid in ecx
mov dl, 5 ; len of return value
int 0x80 ; execute

xor eax, eax ; clean eax
xor ebx, ebx ; for exit (0)
mov al, 1 ; syscall for exit
int 0x80 ; execute

我编译:

nasm -f elf getpid.asm; ld -o getpid getpid.o

然后我使用 strace 来检查:

~# strace ./getpid
getpid() = 17890
write(1, 0X45e2, 5) = -1 EFAULT (Bad address)
_exit(O) = ?

17890d = 45e2h

事实上,我给出的是一个值而不是指向该值的指针。我不知道在这种情况下该怎么做:将 getpid 系统调用的结果放入变量中?然后影响这个变量的地址到ecx?

最佳答案

我找不到(或理解)将十六进制转换为字符串的好代码。但是,我通过使用 C 函数 printf 找到了解决方案

;getpid.asm
extern printf

SECTION .data
msg: db "PID= %d",10,0 ; 10 for \n, 0 and of the string, require for printf

SECTION .text
global main
main:

push ebp ; save ebp
mov ebp, esp ; put the old top of the stack to the bottom
sub esp, 100 ; increase the stack of 100 byte

xor eax, eax ; set eax to 0
mov al, 20 ; syscall getpid
int 0x80 ; execute

push eax ; put the return of the getpid on the stack
push dword msg ; put the string on the stack
call printf
add esp, 8 ; decrease esp of 8, 2 push

leave ; destroy the stack

xor eax, eax ;
xor ebx, ebx ; for exit (0)
mov al, 1 ; syscall for exit
int 0x80 ; execute

编译:

nasm -f elf getpid.asm
gcc -o getpid getpid.o

关于linux - syscall getpid,打印返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com