Linux下execl学习
来源:达缇美食
系统大全为您提供
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:
root@wl-MS-7673:/home
/桌面/c++# cat -n execl.cpp
1/* 执行 /bin/ls -al /ect/passwd */
2#include <unistd.h>/*** File: execl.c**/
3#include <iostream>
4using namespace std;
5int main()
6{
7// 执行/bin目录下的ls, 第一参数为程序名ls, 第二个参数为"-al", 第三个参数为"/etc/passwd"
8
9 if(execl("/bin/ls", "ls", "-al", "/etc/passwd", (char *) 0) < 0)
10
11 {
12cout<<"execl error"<<endl;
13 }
14else
15{
16cout<<"success"<<endl;
17}
18return 0;
19}
root@wl-MS-7673:/home
/桌面/c++# g++ execl.cpp -o execl
root@wl-MS-7673:/home
/桌面/c++# ./execl
-rw-r--r-- 1 root root 1801 11月 28 09:46 /etc/passwd
root@wl-MS-7673:/home
/桌面/c++#
大家可以清楚的看到, 执行/bin目录下的ls, 第一参数为程序名ls, 第二个参数为"-al", 第三个参数为"/etc/passwd",但是没有输出success!!
这是为什么呢?
execl函数特点:
当进程调用一种exec函数时,该进程完全由新程序代换,而新程序则从其main函数开始执行。因为调用exec并不创建新进程,所以前后的进程ID并未改变。exec只是用另一个新程序替换了当前进程的正文、数据、堆和栈段。
用另一个新程序替换了当前进程的正文、数据、堆和栈段。
当前进程的正文都被替换了,那么execl后的语句,即便execl退出了,都不会被执行。
再看一段代码:
root@wl-MS-7673:/home
/桌面/c++# cat -n execl_test.cpp
1#include <unistd.h>
2#include <stdio.h>
3#include <stdlib.h>
4
5int main(int argc,char *argv[])
6{
7if(argc<2)
8{
9 perror("you haven,t input the filename,please try again!
");
10exit(EXIT_FAILURE);
11
12}
13if(execl("./file_creat","file_creat",argv[1],NULL)<0)
14perror("execl error!");
15return 0;
16}
17
root@wl-MS-7673:/home
/桌面/c++# cat -n file_creat.cpp
1#include <stdio.h>
2
3#include <stdlib.h>
4
5#include <sys
pes.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8void create_file(char *filename)
9{
10 if(creat(filename,0666)<0)
11{
12 printf("create file %s failure!
",filename);
13 exit(EXIT_FAILURE);
14 }
15else
16{
17 printf("create file %s success!
",filename);
18 }
19}
20
21int main(int argc,char *argv[])
22{
23 if(argc<2)
24{
25 printf("you haven't input the filename,please try again!
");
26 exit(EXIT_FAILURE);
27 }
28create_file(argv[1]);
29exit(EXIT_SUCCESS);
30}
31
32
root@wl-MS-7673:/home
/桌面/c++# g++ execl_test.cpp -o execl_test
root@wl-MS-7673:/home
/桌面/c++# g++ file_c
file_copy file_copy.cpp file_creat.cpp
root@wl-MS-7673:/home
/桌面/c++# g++ file_creat.cpp -o file_creat
root@wl-MS-7673:/home
/桌面/c++# ./execl_test
you haven,t input the filename,please try again!
: Success
root@wl-MS-7673:/home
/桌面/c++# ./execl_test file
create file file success!
root@wl-MS-7673:/home
/桌面/c++#
以上就是系统大全给大家介绍的如何使的方法都有一定的了解了吧,好了,如果大家还想了解更多的资讯,那就赶紧点击系统大全官网吧。
本文来自系统大全http:///如需转载请注明!推荐:win7纯净版
显示全文