1.作用:在一个进程中调用执行另外一个进程
说点你听得懂的:微信(一个进程)--》支付里面滴滴,京东(另外一个进程)
迅雷(一个进程)--》不小心点到了广告(启动另外一个进程)
2.system的使用
用法一:system调用执行shell命令
用法二:system调用执行另外一个可执行程序
int system(const char *command);
返回值:成功 0 失败 -1
参数:command --》你要执行的命令/程序的名字
3.exec函数族
int execl(const char *path, const char *arg, ...);
参数:path --》你要执行的命令/程序的路径名
arg --》你要执行的命令/程序的参数
int execlp(const char *file, const char *arg, ... );
参数:file --》你要执行的命令/程序的名字
arg --》以列表的形式逐一列举命令/程序的参数
int execle(const char *path, const char *arg, ...char * const envp[] );
参数:path --》你要执行的命令/程序的路径名
arg --》以列表的形式逐一列举命令/程序的参数
envp[] --》你要设置的环境变量
int execv(const char *path, char *const argv[]);
参数:path --》你要执行的命令/程序的路径名
argv[] --》把命令/程序的参数用指针数组保存起来
int execvp(const char *file, char *const argv[]);
参数:file --》你要执行的命令/程序的名字
argv[] --》把命令/程序的参数用指针数组保存起来
int execvpe(const char *file, char *const argv[],
char *const envp[]);
特点:六个函数前面四个字母都一样
l --》list 以列表的形式列举命令/程序的所有参数逐一列举
p --》不用去写命令/程序的路径名,会自动去系统的环境变量中搜索要执行的命令/程序
e --》表示可以去改变进程的环境变量
v --》命令/程序的参数采用指针数组去存放
用法一:exec函数族调用执行shell命令
用法二:exec函数族调用执行另外一个可执行程序
#include "myhead.h"
//execle执行 ls -l
//export PATH=$PAHT:/home/gec 设置环境变量的命令格式
char * const envp[]={NULL};
int main()
{
execle("/bin/ls","ls","-l",NULL,envp);
}
#include "myhead.h"
//execlp执行 ls -l
int main()
{
execlp("ls","ls","-l",NULL);
}
#include "myhead.h"
//execl执行 ls -l
int main()
{
execl("/bin/ls","ls","-l",NULL);
}
#include "myhead.h"
//execv执行 ls -l
int main()
{
char *buf[]={"ls","-l",NULL};
execv("/bin/ls",buf);
}
#include "myhead.h"
int main()
{
system("cp myhead.h /home/gec");
}
#include "myhead.h"
int main()
{
printf("我是另外一个进程,ID是:%hu\n",getpid());
//调用执行刚才编译得到的hello
system("./hello");
}
#include "myhead.h"
int main()
{
printf("我是另外一个进程,ID是:%hu\n",getpid());
//调用执行刚才编译得到的hello
execl("./hello","./hello",NULL);
}
#include "myhead.h"
int main()
{
printf("我是另外一个进程,ID是:%hu\n",getpid());
//调用执行刚才编译得到的hello
//写法一:只写了hello的名字,此时环境变量中必须要有hello
//execlp("hello","./hello",NULL);
//写法二:写了hello所在的绝对路径,此时环境变量中是否有hello无所谓
execlp("/mnt/hgfs/share/execlp执行另外一个可执行程序/hello","./hello",NULL);
}
文章详细介绍了在C语言中如何使用system函数和exec函数族来在一个进程中调用执行另一个进程。通过示例代码展示了如何执行shell命令以及如何执行可执行程序,包括不同函数的参数用法和特点。
1836

被折叠的 条评论
为什么被折叠?



