Linux内核如何装载和启动一个可执行程序

1520阅读 0评论2017-04-08 suphgmh
分类:LINUX

一、可执行文件格式
目标文件有三种格式:

.out   pe    elf

可重定位(relocatable)文件

可执行(executable)文件

共享(object)文件

 

ELF文件格式介绍:

Link  view:

~~~~~~

ELF  header

Program header table(optional)

Section 1

…..

Section n

Section header table

 

Execution view:

ELF header

Program header

Segment 1

……….

Segment n

Section header table

 
查看ELF文件头:

readelf  –h  hello

 

elf文件与进程地址空间的对应:



二、可执行程序的执行环境

点击(此处)折叠或打开

  1. #include <stdio.h>
  2.       #include <stdlib.h>
  3.       #include <unistd.h>
  4.        int main(int argc, char * argv[])
  5.        {
  6.            int pid;
  7.           /* fork another process */
  8.            pid = fork();
  9.            if (pid<0)
  10.        {
  11.            /* error occurred */
  12.            fprintf(stderr,"Fork Failed!");
  13.            exit(-1);
  14.        }
  15.        else if (pid==0)
  16.        {
  17.            /* child process */
  18.            execlp("/bin/ls","ls",NULL);
  19.        }
  20.        else
  21.        {
  22.            /* parent process */
  23.            /* parent will wait for the child to complete*/
  24.            wait(NULL);
  25.            printf("Child Complete!");
  26.            exit(0);
  27.        }
  28.    }

fork创建一个子进程,完全复制父进程。Execve要加载的进程将原来的进程环境给覆盖掉。新子进程堆栈也被清空。命令行参数和环境变量如何加载进新子进程堆栈的呢?

命令行参数和环境变量通过指针的形式,传到系统调用的内核处理函数。内核处理函数创建一个新的用户程序堆栈时,会将命令行产生和环境变量拷贝到用户态堆栈中。

Shell程序 à  execve à  sys_execve

在初始化新程序堆栈时拷贝进去

 
三、
装载时动态链接和运行时动态链接应用举例




 

上一篇:Linux内核创建一个新进程的过程
下一篇:实验环境配置:HelloWorld程序