歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下execl函數學習

Linux下execl函數學習

日期:2017/3/1 9:47:05   编辑:Linux編程

Linux下頭文件
#include <unistd.h>
函數定義
int execl(const char *path, const char *arg, ...);
函數說明
execl()其中後綴"l"代表list也就是參數列表的意思,第一參數path字符指針所指向要執行的文件路徑, 接下來的參數代表執行該文件時傳遞的參數列表:argv[0],argv[1]... 最後一個參數須用空指針NULL作結束。

函數返回值
成功則不返回值, 失敗返回-1, 失敗原因存於errno中,可通過perror()打印

實例1:

[email protected]:/home/linuxidc/桌面/c++# cat -n execl.cpp
1 /* 執行 /bin/ls -al /ect/passwd */
2 #include <unistd.h>/*** File: execl.c**/
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 // 執行/bin目錄下的ls, 第一參數為程序名ls, 第二個參數為"-al", 第三個參數為"/etc/passwd"
8
9 if(execl("/bin/ls", "ls", "-al", "/etc/passwd", (char *) 0) < 0)
10
11 {
12 cout<<"execl error"<<endl;
13 }
14 else
15 {
16 cout<<"success"<<endl;
17 }
18 return 0;
19 }
[email protected]:/home/linuxidc/桌面/c++# g++ execl.cpp -o execl
[email protected]:/home/linuxidc/桌面/c++# ./execl
-rw-r--r-- 1 root root 1801 11月 28 09:46 /etc/passwd
[email protected]:/home/linuxidc/桌面/c++#

大家可以清楚的看到, 執行/bin目錄下的ls, 第一參數為程序名ls, 第二個參數為"-al", 第三個參數為"/etc/passwd",但是沒有輸出success!!

這是為什麼呢?

execl函數特點:

當進程調用一種exec函數時,該進程完全由新程序代換,而新程序則從其main函數開始執行。因為調用exec並不創建新進程,所以前後的進程ID並未改變。exec只是用另一個新程序替換了當前進程的正文、數據、堆和棧段。

用另一個新程序替換了當前進程的正文、數據、堆和棧段。

當前進程的正文都被替換了,那麼execl後的語句,即便execl退出了,都不會被執行。

再看一段代碼:

[email protected]:/home/linuxidc/桌面/c++# cat -n execl_test.cpp
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 int main(int argc,char *argv[])
6 {
7 if(argc<2)
8 {
9 perror("you haven,t input the filename,please try again!\n");
10 exit(EXIT_FAILURE);
11
12 }
13 if(execl("./file_creat","file_creat",argv[1],NULL)<0)
14 perror("execl error!");
15 return 0;
16 }
17
[email protected]:/home/linuxidc/桌面/c++# cat -n file_creat.cpp
1 #include <stdio.h>
2
3 #include <stdlib.h>
4
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 void create_file(char *filename)
9 {
10 if(creat(filename,0666)<0)
11 {
12 printf("create file %s failure!\n",filename);
13 exit(EXIT_FAILURE);
14 }
15 else
16 {
17 printf("create file %s success!\n",filename);
18 }
19 }
20
21 int main(int argc,char *argv[])
22 {
23 if(argc<2)
24 {
25 printf("you haven't input the filename,please try again!\n");
26 exit(EXIT_FAILURE);
27 }
28 create_file(argv[1]);
29 exit(EXIT_SUCCESS);
30 }
31
32
[email protected]:/home/linuxidc/桌面/c++# g++ execl_test.cpp -o execl_test
[email protected]:/home/linuxidc/桌面/c++# g++ file_c
file_copy file_copy.cpp file_creat.cpp
[email protected]:/home/linuxidc/桌面/c++# g++ file_creat.cpp -o file_creat
[email protected]:/home/linuxidc/桌面/c++# ./execl_test
you haven,t input the filename,please try again!
: Success
[email protected]:/home/linuxidc/桌面/c++# ./execl_test file
create file file success!
[email protected]:/home/linuxidc/桌面/c++#

Copyright © Linux教程網 All Rights Reserved