【发布时间】:2009-11-06 22:24:43
【问题描述】:
这是一个现场面试问题,我很困惑。
我被要求为 linux 编写一个 Hello world 程序.. 那也是 不使用系统中的任何库。我想我必须使用 系统调用或其他东西..代码应该使用 -nostdlib 和 -nostartfiles 选项..
如果有人能帮忙就好了..
【问题讨论】:
-
什么工作,写操作系统内核?
这是一个现场面试问题,我很困惑。
我被要求为 linux 编写一个 Hello world 程序.. 那也是 不使用系统中的任何库。我想我必须使用 系统调用或其他东西..代码应该使用 -nostdlib 和 -nostartfiles 选项..
如果有人能帮忙就好了..
【问题讨论】:
$ cat > hwa.S
write = 0x04
exit = 0xfc
.text
_start:
movl $1, %ebx
lea str, %ecx
movl $len, %edx
movl $write, %eax
int $0x80
xorl %ebx, %ebx
movl $exit, %eax
int $0x80
.data
str: .ascii "Hello, world!\n"
len = . -str
.globl _start
$ as -o hwa.o hwa.S
$ ld hwa.o
$ ./a.out
Hello, world!
【讨论】:
看看example 4(不会因可移植性而获奖):
#include <syscall.h>
void syscall1(int num, int arg1)
{
asm("int\t$0x80\n\t":
/* output */ :
/* input */ "a"(num), "b"(arg1)
/* clobbered */ );
}
void syscall3(int num, int arg1, int arg2, int arg3)
{
asm("int\t$0x80\n\t" :
/* output */ :
/* input */ "a"(num), "b"(arg1), "c"(arg2), "d"(arg3)
/* clobbered */ );
}
char str[] = "Hello, world!\n";
int _start()
{
syscall3(SYS_write, 0, (int) str, sizeof(str)-1);
syscall1(SYS_exit, 0);
}
编辑:正如下面Zan Lynx 所指出的,sys_write 的第一个参数是file descriptor。因此,这段代码执行了将"Hello, world!\n" 写入stdin (fd 0) 而不是stdout (fd 1) 的罕见事情。
【讨论】:
【讨论】:
.global _start
.text
_start:
mov $1, %rax
mov $1, %rdi
mov $yourText, %rsi
mov $13, %rdx
syscall
mov $60, %rax
xor %rdi, %rdi
syscall
yourText:
.ascii "Hello, World\n"
您可以使用gcc 组装和运行它:
$ vim hello.s
$ gcc -c hello.s && ld hello.o -o hello.out && ./hello.out
或使用as:
$as hello.s -o hello.o && ld hello.o -o hello.out && ./hello.out
【讨论】:
您必须直接与操作系统对话。你可以 write 到文件描述符 1,(stdout),通过这样做:
#include <unistd.h>
int main()
{
write(1, "Hello World\n", 12);
}
【讨论】:
shell 脚本呢?我在问题中没有看到任何编程语言要求。
echo "Hello World!"
【讨论】:
echo(1) 根本不使用 C 标准库,我很确定这里有一个隐含的“C”语言(或者至少是一个编译的语言)。