库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

来源:互联网 发布:万科金域名邸二手房 编辑:程序博客网 时间:2024/06/04 20:09

<span style="font-family: Arial, 'Hiragino Sans GB', SimSun, 宋体, serif; background-color: rgb(255, 255, 255);">张磊+原创作品转载请注明出处 + 《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000 </span>

使用库函数调用 API。

#include <stdio.h>#include <unistd.h>int main(){pid_t fpid;//fpid表示 fork 函数返回的值fpid = fork();if(fpid < 0)printf("error in fork!\n");else if (fpid == 0)printf("I am the child process,my process id is %d\n",getpid());else printf("I am the parent process, my process id is %d\n",getpid());return 0;}

调用 fork()后,返回一个 fpid 的值,根据 fpid 的值来判断是父进程还是子进程,或者是库函数 API调用错误。

下面是 C 语言中嵌入汇编代码调用库函数 fork()函数

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>pid_t _fork_asm_(){pid_t tt;asm volatile("mov $0x2, %%eax\n\t""int $0x80\n\t""mov %%eax, %0\n\t":"=m" (tt));return tt;}int main(int argc, const char *argv[]){pid_t tt;tt = _fork_asm_();if (tt == 0){printf("I am the child process,my pid is %d\n",getpid());}else{printf("I am the parent process,my pid is %d\n",getpid());}return 0;}
由于没有参数传入,在嵌入汇编代码时,直接调用
mov $0x2, %%eax

2i386forksys_forkstub32_fork
由于 fork 函数在 i386机器中为2号系统调用,所有直接调用2号进程。

int $0x80
系统调用函数结束会产生80号系统中断来还原系统调用之前的现场,程序继续往下执行。

mov %%eax, %0
返回值存储到 eax 中。

执行结果如图






0 0
原创粉丝点击