主要通過在一個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 );
}
}
