Settings | Sign in | Sign up

There are currently 7 posts.

【原创】模拟操作系统运行应用程序的C程序

Floor 1 巨大八爪鱼 2/26/16 18:33
【OS.c】
#include <stdio.h>

char memory[256]; // 假定这个就是“操作系统”的一块内存

int main()
{
    char *pStr;
    int size, n;
   
    // 将要运行的程序读入“内存”
    FILE *fp = fopen("app.hrb", "r");
    fseek(fp, 0, SEEK_END);
    size = ftell(fp) - 1; // size = 文件大小 - 1
    fseek(fp, 1, SEEK_SET); // 必须跳过文件中的第一个字节
    fread(memory, size, 1, fp); // 从第二个字节开始读取,一直到文件结束
    fclose(fp);
   
    // 运行“程序”, 并获取“程序”向“操作系统”返回的值
    n = ((int (*)())memory)();
    pStr = memory + n;
    puts(pStr); // 输出程序中的字符串
   
    return 0;
}
Floor 2 巨大八爪鱼 2/26/16 18:34
【OSHead.asm】
; 这个文件里面什么也不用写
Floor 3 巨大八爪鱼 2/26/16 18:35
编译“操作系统”:
nasm -f elf OSHead.asm
gcc -m32 OSHead.o OS.c -o OS
Floor 4 巨大八爪鱼 2/26/16 18:35
【应用程序 app.asm】
ORG -1 ; 告诉编译器,这个程序将会被读到&memory[-1]的地址上
MOV EAX, msg ; 该“应用程序”会将msg的地址作为返回值返回给“操作系统”
RET ; 返回

msg:
    DB "I'm from a program."
    DB 0
【编译“应用程序”】
nasm app.asm -o app.hrb
Floor 5 巨大八爪鱼 2/26/16 18:36
最后,运行./OS,输出:
$ ./OS
I'm from a program.

这表明,“操作系统“ OS成功运行了“应用程序” app.hrb。
Floor 6 巨大八爪鱼 2/26/16 18:39
【补充】
这里的OS.c必须被编译成32位的,才能正确运行32位的app.hrb。
如果电脑是64位的话,必须给gcc安装:
sudo apt-get install libc6-dev-i386
才能编译32位的c程序。
Floor 7 巨大八爪鱼 2/29/16 23:47
因此,应用程序实际上是拿给CPU执行的,并不是操作系统在解释执行。操作系统和应用程序本质上都是由机器代码构成的,其性质基本相同。

Content converter:

Reply the post
Content:
User: You are currently anonymous.
Captcha:
Unclear? Try another one.
©2010-2025 Purasbar Ver3.0 [Mobile] [Desktop]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported license.