EXEC家族函数一览
![在这里插入图片描述](https://img-blog.csdnimg.cn/167026e3fc9e4e79a7dadb7bf56322c9.png#pic_center)
该家族的函数的功能基本一致:与另一个程序进行交互,这个程序可以是shell程序,单纯的shell命令或者C/C++程序等等,只要系统能识别运行都算。
不过衍生这么多不同的函数,肯定也略有区别:无非就是调用的方式不一样(主进程调用还是子进程进行调用),而且填写的参数方式也略有区别。
以execl抛砖引玉
函数原型:
int execl(const char *path, const char *arg, ...);
/*
path:代码可执行程序的路径,一般以绝对路径为主,如果设置设置了相应的环境变量,那么相对路径也行
arg:后面这个就是比较麻烦的一点,看着简单无非就是传入简单的参数,但很坑
...:代表可接受多个参数的输入
最后一点,根据官方给的资料,最后一个参数必须要填NULL,代表结束
/*
与shell交互
shell命令
以常见的shell命令为例:ps aux
该命令是静态显示当前linux的所有进程信息
那么代码可以这样写:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int main()
{
int ret = 0;
//注意第一个参数的绝对路径,不是/bin/bash,bash只是用自己的方式去解释这些shell命令给系统
ret = execl("/bin/ps","ps","a", "u", "x", NULL);
if(ret < 0){
printf("errno is %d\n", errno);
perror("failed to execute execl!!!\n");
}
return 0;
}
shell脚本
并非只支持shell脚本,其他脚本也类似
现在建一个skt.sh脚本放在/home目录下
#!/bin/bash
echo "directory is:"
pwd
echo "showed"
ps aux
exit 0
C程序要这样写
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int main()
{
int ret = 0;
//现在可以将第一个参数变为/bin/bash了
ret = execl("/bin/bash","sh","/home/skt.sh", NULL);
if(ret < 0){
printf("errno is %d\n", errno);
perror("failed to execute execl!!!\n");
}
return 0;
}
与其他程序交互
以C程序为例吧,其余程序也类似
现写了一个C程序名为proc,放在/home目录下
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
int main()
{
int ret = 0;
//现在可以将第一个参数变为刚才那个程序的路径
//后面的参数,看情况需要还是不需要填写,我写的这个proc,就固定创建多个子进程,然后再kill掉,
//不需要多余参数
ret = execl("/home/proc", NULL);
if(ret < 0){
printf("errno is %d\n", errno);
perror("failed to execute execl!!!\n");
}
return 0;
}