使用库函数API和C代码中嵌入汇编代码两种方式实现对sysinfo的系统调用

本例对116号系统调用sysinfo,通过c语言和嵌入式汇编语言来实现。

1.C语言实现过程如下:

打开VIM编辑器边集sysinfo.c文件,如下

#include<stdio.h>
#include<sys/sysinfo.h>

int main()
{
    struct sysinfo info;
    if(sysinfo(&info)<0)
    {
        perror("sysinfo failed!");
        return -1;
    }
    printf("uptime  %ld\n",info.uptime);
    printf("totalram    %ld\n",info.totalram);
    printf("freeswap    %ld\n",info.freeswap);
    return 0;
}
编译:gcc sysinfo.c -o sysingfo

执行:./sysinfo得到如下结果


2.嵌入式汇编如下:

打开VIM编辑器边集sysinfo_asm.c文件,如下

#include <stdio.h>
#include <sys/sysinfo.h>

int main()
{
    struct sysinfo info;
    asm volatile(
        "mov $0,%%ebx\n\t"
        "mov $0xd,%%eax\n\t"
        "int $0x80\n\t"
        "mov %%eax,%0\n\t"
        :"=m"(info)
            );
    printf("uptime  %ld\n",info.uptime);
    printf("totalram    %ld\n",info.totalram);
    printf("freeswap    %ld\n",info.freeswap);
    return 0;
}

编译:gcc sysinfo_asm.c -o sysingfo_asm

执行:./sysinfo_asm得到如下结果


sysinfo系统调用的定义文件在sysinfo.h中,结构体如下,

struct sysinfo {
    long uptime;             /* Seconds since boot */
    unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
    unsigned long totalram;  /* Total usable main memory size */
    unsigned long freeram;   /* Available memory size */
    unsigned long sharedram; /* Amount of shared memory */
    unsigned long bufferram; /* Memory used by buffers */
    unsigned long totalswap; /* Total swap space size */
    unsigned long freeswap;  /* swap space still available */
    unsigned short procs;    /* Number of current processes */
    unsigned long totalhigh; /* Total high memory size */
    unsigned long freehigh;  /* Available high memory size */
    unsigned int mem_unit;   /* Memory unit size in bytes */
    char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};

本文选择了其中的三个参数,uptime,totalram,freeswap,其他参数的使用方式类同。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值