linux - Using printf in assembly leads to an empty ouput -
i try use printf
assembler code, minimal example should print hello
stdout:
.section .rodata hello: .ascii "hello\n\0" .section .text .globl _start _start: movq $hello, %rdi #first parameter xorl %eax, %eax #0 - number of used vector registers call printf #exit movq $60, %rax movq $0, %rdi syscall
i build with
gcc -nostdlib try_printf.s -o try_printf -lc
and when run it, seems work: string hello
printed out , exit status 0
:
xxx$ ./try_printf hello xxx$ echo $? 0 xxx$
but when try capture text, obvious, not working properly:
xxx$ output=$(./try_printf) xxx$ echo $output xxx$
the variable output
should have value hello
, empty.
what wrong usage of printf
?
as michael explained, ok link c-library dynamically. how introduced in "programming bottom up" book (see chapter 8).
however important call exit
c-library in order end program , not bypass it, wrongly did calling exit-syscall
. hinted michael, exit lot of clean up flushing streams.
that happened: explained here, c-library buffers the standard streams follows:
- no buffering standard error.
- if standard out/in terminal, line-buffered.
- if standard out/in not terminal, fully-buffered , flush needed in end of writing.
which case applies decided when printf
called first time stream.
so if printf_try
called directly in terminal, output of program can seen because hello
has \n
@ end (which triggers flush in line-buffered mode) , terminal, 2. case.
calling printf_try
via $(./printf_try)
means stdout no longer terminal (actually don't know whether is temp file or memory file) , 3. case in effect - there need explicit flush i.e. call c-exit
.
Comments
Post a Comment