首页 > 代码库 > linux系统调用

linux系统调用

借鉴了网易云课堂上孟宁老师的《linux内核分析》公开课上的内容

直接上函数:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t id;
    id = getpid();
    printf("The id of this process is %ld\n", (long)id);
    
    return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t id;
    //id = getpid();

    asm volatile(
            "mov $0,%%ebx\n\t"
            "mov $0x14,%%eax\n\t"  //0x14是getpid系统调用号,使用eax寄存器
            "int $0x80\n\t"        //产生中断,从用户态进入内核态,int指令在进入内核态之前会进行寄存器的保存工作
            "mov %%eax,%0\n\t"     //系统调用返回值
            : "=m" (id)
        );
    printf("The id of this process is %ld\n", (long)id);
    
    return 0;
}

下面是系统调用需要传递参数,mkdir函数

#include <sys/stat.h>
#include <sys/types.h>

int main(void)
{
    const char path[] = "test";
    if (0 == mkdir(path, S_IRWXU))
        return 0;
    else
        return -1;
}
#include <sys/stat.h>
#include <sys/types.h>

int main(void)
{
    const char path[] = "test";
    mode_t mode = S_IRWXU;
    int rst;
    
    asm volatile(
            "mov $0x27,%%eax\n\t" 
            "int $0x80\n\t" 
            "mov %%eax,%0\n\t"  
            : "=m" (rst)
            : "b" (path), "c" (mode)    //传递的参数按先后通过ebx和ecx两个寄存器
        );
    if (0 == rst)
        return 0;
    else
        return -1;
}

 

linux系统调用