Linux下系统调用之exec函数族探索

浏览:
字体:
发布时间:2013-12-09 23:23:37
来源:

主要通过在一个C程序代码调用另外一个C代码生成的执行文件来说明。

说是exec系统调用,实际上在Linux中,并不存在一个exec()的函数形式,exec指的是一组函数,一共有6个,分别是:

  #include <unistd.h>

  extern char **environ;

  int execl(const char *path, const char *arg, ...);

  int execlp(const char *file, const char *arg, ...);

  int execle(const char *path, const char *arg, ..., char *const envp[]);

  int execv(const char *path, char *const argv[]);

  int execvp(const char *file, char *const argv[]);

  int execve(const char *path, char *const argv[], char *const envp[]);

返回值

  如果执行成功则函数不会返回,执行失败则直接返回-1,失败原因存于errno 中。

l表示以参数列表的形式调用

  v表示以参数数组的方式调用

  e表示可传递环境变量

  p表示PATH中搜索执行的文件,如果给出的不是绝对路径就会去PATH搜索相应名字的文件,如PATH没有设置,则会默认在/bin,/usr/bin下搜索。

具体示例:

#include <stdio.h>void main() {     int i;     if ( fork() == 0 )      {           /* 子进程程序 *///        for ( i = 1; i <10; i ++ )            printf("This is child process/n");     }       else     {          /* 父进程程序*/  //     for ( i = 1; i <10; i ++ )        printf("This is parent process/n");    }   }

运行结果:

/


调用上面生成2进制文件:

#include <stdio.h>#include <stdlib.h>#include<unistd.h>#include <errno.h>//char command[256];void main(){   int rtn; /*子进程的返回数值*/       /* 从终端读取要执行的命令 */       printf( ">" );    //   fgets( command, 256, stdin );      // command[strlen(command)-1] = 0;       if ( fork() == 0 ) {/* 子进程执行此命令 *///          execlp( "test", NULL );         // execlp( "test", NULL );       // execlp("ls","-al",NULL);        execl("/home/buyingfei888/test",NULL);          /* 如果exec函数返回,表明没有正常执行命令,打印错误信息*/         // perror( );          exit( errno );       }          else {/* 父进程, 等待子进程结束,并打印子进程的返回值 */          wait ( &rtn );          printf( " child process return %d/n", rtn );       }}

运行结果:


>更多相关文章
24小时热门资讯
24小时回复排行
资讯 | QQ | 安全 | 编程 | 数据库 | 系统 | 网络 | 考试 | 站长 | 关于东联 | 安全雇佣 | 搞笑视频大全 | 微信学院 | 视频课程 |
关于我们 | 联系我们 | 广告服务 | 免责申明 | 作品发布 | 网站地图 | 官方微博 | 技术培训
Copyright © 2007 - 2024 Vm888.Com. All Rights Reserved
粤公网安备 44060402001498号 粤ICP备19097316号 请遵循相关法律法规
');})();