回顾
1 父进程调用 frok 函数 克隆出子进程 并且给他拷贝了空间
2 两者操作互不影响 且 内存不能共享 。
继续冲
exec 函数族
前面说的 父进程调用 frok 函数 克隆出子进程 并且给他拷贝了空间
两者操作互不影响 且 内存不能共享 。
这样会导致浪费了空间内存
如果用exec 就会节省空间 并且会多执行一个命令 或者更多命令
exec 函数族的第一种函数说明和实验
path :执行程序路径
arg :执行程序参数
第一个 arg:占位
占位:占位符的意思 随意写就行了 最好和执行参数一样 为了好区分
后面的arg: 命令参数 多少都行 最后以NULL 结尾就行了
直接操作
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int a=100;
int main()
{
pid_t a;
a=fork();
if(a>0)
{
a+=200;
printf("!!!A=%d\n",a);
printf("father pid is %d\n",getpid());
}
else if(a==0)
{
a-=50;
printf("*****a=%d\n",a);
printf("child pid is %d ppid is %d \n",getpid(),getppid());
}
execl("/bin/ls","ls","-l","NULL");//多余命令 不占用空间
return 0;
}
如果只是实现一个命令参数
/bin/ls :执行的程序路径 ls :执行参数(可以不要 也可以随意 只是作为辅助作用) -l 是命令参数 以 NULL结尾
(execl 函数 的 绝对路径选到不能选为止)
多执行 hello.c 呢
第一
第二
gcc hello.c -o hello
./hello 运行可执行文件
. 为命令 / 在当前目录下 找到 xxx文件
hello 为命令参数
怎么改呢
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int a=100;
int main()
{
pid_t a;
a=fork();
if(a>0)
{
a+=200;
printf("!!!A=%d\n",a);
printf("father pid is %d\n",getpid());
}
else if(a==0)
{
a-=50;
printf("*****a=%d\n",a);
printf("child pid is %d ppid is %d \n",getpid(),getppid());
}
execl("/home/ycy/process/hello",“hello”,"hello",NULL);
return 0;
}
因为 hello 就是命令参数了 所以占位符可以不写 写也可以
写法 2 excel("/home/ycy/process/hello","hello",NULL);
exec 函数族的第二种函数说明和实验
和excel 少了一个参数而已 少了一个特定路径
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int a=100;
int main()
{
pid_t a;
a=fork();
if(a>0)
{
a+=200;
printf("!!!A=%d\n",a);
printf("father pid is %d\n",getpid());
}
else if(a==0)
{
a-=50;
printf("*****a=%d\n",a);
printf("child pid is %d ppid is %d \n",getpid(),getppid());
}
excelp("ls","ls","-l","NULL");//多余命令 不占用空间
return 0;
}
excel 获取系统时间
date 指令可以获取 时间 并且可以看到他的所在的路径
。
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int i = 0 ;
printf("this is system date:\n");
if(execl("/bin/date","date",NULL)==-1){
printf("execl is failed\n");
perror("why");
}
printf("Execution continues after failure\n");
return 0;
}
excel 失败后继续往下执行
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
int i = 0 ;
printf("this is system date:\n");
if(execl("./date","date",NULL)==-1){
printf("execl is failed\n");
perror("why");
}
printf("Execution continues after failure\n");
return 0;
}
因为 当前路径没有 date , execl 函数 就会 失败 就会继续往下执行