1

I'm a newbie to x86 assembly (Intel syntax) and have been playing around with some simple instructions using inline GCC. I have successfully managed to do manipulation of numbers and control flow and am now tackling standard input and output using interrupts. I am using Mac OS X and forcing compilation for 32-bit using the -m32 GCC flag.

I have the following for printing a string to standard output:

char* str = "Hello, World!\n";
int strLen = strlen(str);
asm
{
    mov eax, 4
    push strLen
    push str
    push 1
    push eax
    int 0x80
    add esp, 16
}

When compiled and run this prints Hello, World! to the console! However, when I try to do some reading from standard input, things don't work as well:

char* str = (char*)malloc(sizeof(char) * 16);
printf("Please enter your name: ");
asm
{
    mov eax, 3
    push 16
    push str
    push 0
    push eax
    int 0x80
    add esp, 16
}
printf("Hello, %s!\n", str);

When run, I get a prompt, but without the "Please enter your name: " string. When I enter some input and hit Enter, the entry string is printed as well as the expected output, e.g.

Please enter your name: Hello, Joe Bloggs
!

How do I get the entry string to appear in the expected location, before the user enters any input?

4

1 回答 1

4

printf使用 stdio 进行写入,该 stdio 进行缓冲(即,写入的内容不会立即得到输出)。在发送系统调用以读取之前,您需要先fflush(stdout)调用(因为系统调用绕过 stdio 并且对缓冲区一无所知)。

此外,正如 Kerrek SB 所指出的,您asm没有破坏列表,也不是volatile. 这意味着 gcc 可以自由地将您的汇编代码重新定位到函数中的其他位置(因为它可以自由地假设您的汇编代码没有副作用),这可能会产生与您期望的不同的效果。我建议你使用asm volatile.

于 2013-08-27T23:34:18.920 回答