|
今天新學的execl開始沒太弄明白他的參數(shù)列表,上網(wǎng)查了好多終于搞定。簡單記錄以下以免以后忘了:
execl()函數(shù)聲明如下: extern int execl(_const char *_path,const char *_argv[],...,NULL) 簡單解釋:函數(shù)execl()返回值定義為整形,如果執(zhí)行成功將不返回!執(zhí)行失敗返回-1。 參數(shù)列表中char *_path為所要執(zhí)行的文件的絕對路徑,從第二個參數(shù)argv開始為執(zhí)行新的文件所需的參數(shù),最后一個參數(shù)必須是控指針(我為了簡便用NULL代替)。 舉個例子: 一 先來個新程序不帶參數(shù)的簡單例子: //execl.c #include<stdio.h> #include<unistd.h> int main(int argc,char *argv[]) { int test; if((test=execl("/home/crosslandy/Linux/exec/hello",argv[1],NULL))==-1) printf("error\n"); return 0; } //hello.c #include<stdio.h> int main(int argc,char *argv[]) { int i; printf("hello world\n"); for(i=0;i<argc;i++) { printf("parameter %d is:%s\n",i,argv[i]); } return 0; } 解釋一下: execl.c文件: 1定義的整形test用來判斷execl是否執(zhí)行成功,如果失敗返回-1輸出error; 2第一個參數(shù)"/home/crosslandy/Linux/exec/hello"為我所要執(zhí)行的文件的絕對路徑(記住在絕對路徑后要寫上所要執(zhí)行的文件的文件名); 3第二個參數(shù)為所要執(zhí)行的新文件的第一個參數(shù),本例子即為./hello 4第三個參數(shù)為空指針(因為hello這個程序不需要參數(shù)所以直接寫最后一個參數(shù)空指針); hello.c文件: 地球人都知道的hello world。只不過在后面我加上了執(zhí)行該文件是在終端所輸入的參數(shù)argv[]并對其進行輸出。 在終端執(zhí)行的時候結(jié)果如下: [crosslandy@localhost exec]$ ./execl ./hello hello world parameter 0 is:./hello 二 再來個帶參數(shù)的例子: //execl.c #include<stdio.h> #include<unistd.h> int main(int argc,char *argv[]) { int test; if((test=execl("/home/crosslandy/Linux/exec/hello",argv[1],argv[2],NULL))==-1) printf("error\n"); return 0; } //hello.c #include<stdio.h> int main(int argc,char *argv[]) { int i; printf("hello world\n"); for(i=0;i<argc;i++) { printf("parameter %d is:%s\n",i,argv[i]); } return 0; } 解釋一下: 新的例子里我只對execl.c進行了小修改即紅色部分argv[2],表示在調(diào)用execl函數(shù)執(zhí)行新文件時多添加了一個參數(shù)。 在終端執(zhí)行的時候結(jié)果如下: [crosslandy@localhost exec]$ ./execl ./hello first_parameter hello world parameter 0 is:./hello parameter 1 is:first_parameter |
|
|