linux下关于execve函数的简单解析

execve(执行文件)
在父进程中fork一个子进程,在子进程中调用exec函数启动新的程序。exec函数一共有六个,其中execve为内核级系统调用,其他(execl,execle,execlp,execv,execvp)都是调用execve的库函数。废话不多少,看实例:

processimage.c文件:

//用来替换进程映象的程序
#include 
#include 
#include 
#include 

int main(int args,char *argv[],char **environ)
{
    int i;
   
    printf("I am a process image!\n");
    printf("My pid = %d,parentId = %d\n",getpid(),getppid());
    printf("uid = %d,gid = %d\n",getuid(),getgid());

    for(i=0;i

execve.c文件:

 1 //execve程序实例,这里使用execve函数
  2 #include 
  3 #include 
  4 #include 
  5 #include 
  6 
  7 int main(int args,char *argv[],char **environ)
  8 {
  9     pid_t pid;
 10     int stat_val;
 11 
 12     printf("Exec example!\n");
 13     pid = fork();
 14 
 15     switch(pid)
 16     {
 17     case -1:
 18         perror("Process Creation failed!\n");
 19         exit(1);
 20     case 0:
 21         printf("Child process is running\n");
 22         printf("My pid = %d,parentId = %d\n",getpid(),getppid());
 23         printf("uid = %d,gid = %d\n",getuid(),getgid());
 24         execve("processimage",argv,environ);
 25         printf("process never go to here!\n");
 26         exit(0);
 27     default:
 28         printf("Parent process is running!\n");
 29         break;
 30     }
 31     wait(&stat_val);
 32     exit(0);
 33 }

执行结果:

[root@localhost code]# ./execve test evecve
Exec example!
Parent process is running!
Child process is running
My pid = 2819,parentId = 2818
uid = 0,gid = 0
I am a process image!
My pid = 2819,parentId = 2818
uid = 0,gid = 0
argv[0]:./execve
argv[1]:test
argv[2]:evecve

从执行的结果中可以看出,新进程保持了原来进程的ID,父进程ID,实际用户ID,实际组ID。同时我们还可以发现当调用新的程序后,原有的子程序的镜像被替代,不被执行了。


你可能感兴趣的:(Linux)