system
system("") 接收一个命令参数并执行命令,操作系统在解释命令参数时容易出错,而且通过拼接字符串可能造成系统入侵,不安全
exec()函数
通过运行其他程序来替换当前进程,新老进程具有相同的pid,声明在unistd.h中
exec是最基本的函数,还有一些扩展函数,每个exec函数后可能跟1,2个字符,只可能是l, v, p, e,
l: 参数列表
v:参数数组或向量
p: 根据path查找
e: 环境变量
每个字母代表了相应的功能,l , v总是在 p, e之前
#includeint execl(const char *pathname, const char *arg0, ..., /* (char *)0 */);int execlp(const char *filename, const char *arg, ..., /* (char *)0 */);int execle(const char *pathname, const char *arg0, ..., /* (char *)0, char *const envp[] */);int execv(const char *pathname, char *const argv[]);int execvp(const char *filename, char *const argv[]);int execve(const char *pathname, char *const argv[], char *const envp[]);
在 linux ,要成功执行 uname r 这个命令,exec 家族各个函数的例子为
execv
char *arg[] = {"uname", "r", NULL}; execv("/bin/uname", arg);
execl
execl("/bin/uname", "uname", "r", NULL);
execve
char *arg[] = {"uname", "r", NULL}; char *env[] = {NULL}; execve("/bin/uname", arg, env);
execvp
char *arg[] = {"uname", "r", NULL}; execvp("uname", arg);
execle
char *env[] = {NULL}; execle(“/bin/uname", "uname", "r", NULL, env);
exelp
execlp("uname", "uname", "r", NULL);
调用系统进程
#include#include //You need this for the exec() functions#include //You need this for the errno variable.#include //This will let you display errors with strerror().int main(){ if (execl("/sbin/ifconfig","/sbin/ifconfig",NULL)==-1)//Use execl() because you have the path to the program file,If execl() returns -1, it failed, so we should probably look for ipconfig if (execlp("ipconfig","ipconfig",NULL)== -1) { //execlp() will let us find the ipconfig command on the path fprintf(stderr, "Cannot run ipconfig: %s",strerror(errno));//The strerror() function will display any problems return 1; } return 0;}
调用自定义进程
dinner_info.c ,路径为/home/weiwei/Desktop/c/system/dinner_info.c
#include#include int main(int argc, char *argv[]){ printf("Diners: %s\n", argv[1]); printf("Juice: %s\n", getenv("JUICE")); return 0;}
main.c
#include#include #include #include #include int main(int argc, char *argv[]){ printf(" the Father process! "); char *my_env[] = {"JUICE=peach and apple", NULL};//Each variable in the environment is name=value,The last item in the array must be NULL.if(execle("/home/weiwei/Desktop/c/system/dinner_info", "/home/weiwei/Desktop/c/system/dinner_info", "4", NULL, my_env)==-1){//execle passes a list of arguments andan environment printf(" the process is wrong!! "); fprintf(stderr, "Cannot run : %s",strerror(errno));} return 0;}
克隆进程
一旦调用exec函数,原来的程序马上就被终止掉,所以上图中的for循环只会运行第一个,如果在启动另一个进程的时候同时让原进程继续运行,使用fork()克隆当前进程,新建副本将从同一行开始运行相同的程序,只有pid与原进程不同,原进程是父进程,新建副本为子进程