Linux下execl学习
发布时间:2022-11-23 00:31:20阅读:65次来源:HarmonyOS下载网 系统大全为您提供Linux下头文件#include<unistd.h>函数定义intexecl(constchar*path,constchar*arg,...);函数说明execl()其中后缀"l"代表list也就是参数列表的意思,第一参数path字符指针所指向要执行的文件路径,接下来的参数代表执行该文件时传递的参数列表:argv[0],argv[1]...最后一个参数须用空指针NULL作结束。函数返回值成功则不返回值,失败返回-1,失败原因存于errno中,可通过perror()打印实例1:root@wl-MS-7673:/home/桌面/c++#cat-nexecl.cpp1 /*执行/bin/ls-al/ect/passwd*/2 #include<unistd.h>/***File:execl.c**/3 #include<iostream>4 usingnamespacestd;5 intmain()6 {7 //执行/bin目录下的ls,第一参数为程序名ls,第二个参数为"-al",第三个参数为"/etc/passwd"89 if(execl("/bin/ls","ls","-al","/etc/passwd",(char*)0)<0)1011 {12 cout<<"execlerror"<<endl;13 }14 else15 {16 cout<<"success"<<endl;17 }18 return0;19 }root@wl-MS-7673:/home/桌面/c++#g++execl.cpp-oexeclroot@wl-MS-7673:/home/桌面/c++#./execl-rw-r--r--1rootroot180111月2809:46/etc/passwdroot@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-nexecl_test.cpp1 #include<unistd.h>2 #include<stdio.h>3 #include<stdlib.h>45 intmain(intargc,char*argv[])6 {7 if(argc<2)8 {9 perror("youhaven,tinputthefilename,pleasetryagain!");10 exit(EXIT_FAILURE);1112 }13 if(execl("./file_creat","file_creat",argv[1],NULL)<0)14 perror("execlerror!");15 return0;16 }17root@wl-MS-7673:/home/桌面/c++#cat-nfile_creat.cpp1 #include<stdio.h>23 #include<stdlib.h>45 #include<syspes.h>6 #include<sys/stat.h>7 #include<fcntl.h>8 voidcreate_file(char*filename)9 {10 if(creat(filename,0666)<0)11 {12 printf("createfile%sfailure!",filename);13 exit(EXIT_FAILURE);14 }15 else16 {17 printf("createfile%ssuccess!",filename);18 }19 }2021 intmain(intargc,char*argv[])22 {23 if(argc<2)24 {25 printf("youhaven'tinputthefilename,pleasetryagain!");26 exit(EXIT_FAILURE);27 }28 create_file(argv[1]);29 exit(EXIT_SUCCESS);30 }3132root@wl-MS-7673:/home/桌面/c++#g++execl_test.cpp-oexecl_testroot@wl-MS-7673:/home/桌面/c++#g++file_cfile_copyfile_copy.cppfile_creat.cpproot@wl-MS-7673:/home/桌面/c++#g++file_creat.cpp-ofile_creatroot@wl-MS-7673:/home/桌面/c++#./execl_testyouhaven,tinputthefilename,pleasetryagain!:Successroot@wl-MS-7673:/home/桌面/c++#./execl_testfilecreatefilefilesuccess!root@wl-MS-7673:/home/桌面/c++# 以上就是系统大全给大家介绍的如何使的方法都有一定的了解了吧,好了,如果大家还想了解更多的资讯,那就赶紧点击系统大全官网吧。本文来自系统大全http://www.win7cn.com/如需转载请注明!推荐:win7纯净版