execv函数族:系统来调用某程序模块
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
本质:1、调用此函数时(成功的执行),调用的进程模块会替换现有的进程信息。
元素为NULL
2、execve才是系统内核函数,上述都会调用此函数来完成的功能
从指定路径下查找
int execv(const char *path, char *const argv[]);
path:可执行文件的路径
argv:就是用户传递的参数 argv[0] argv[1] argv[2]注:最后一个数组
int execl(const char *path, const char *arg, ...);
path:可执行文件的路径
arg:传递的参数(一定要传递NULL)
execv 通过 argv 来获取 ls -l / 的路径,来替代系统的 /bin/ls 路径.
#include<iostream>
#include<unistd.h>
using namespace std;
//进程:分配空间
int main()
{cout<<"程序开始执行啦,成为进程"<<endl;//需要执行某程序模块 a.out a.out a b c char* argv[5]={"ls","-l","/",NULL};execv("/bin/ls",argv);//argv[0] argv[1] argv[2] int i=0;for(i=0;i<100;i++){cout<<i<<endl;}cout<<"进程结束执行"<<endl;
}
execvp 的"ls"从环境变量中查找某 ls (也可以是其他命令) .
#include<iostream>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
using namespace std;
int main()
{
//本进程:1、去执行ls可执行文件 2、求1-100的和cout<<"a.out开始执行啦"<<getpid()<<endl;//执行ls的可执行文件//创建子进程,在子进程执行 模块int pid=fork();if(pid>0)//父进程{wait(NULL);}else if(0==pid)//子进程模块:execv替换进程模块{char* argv[]={"ls","/",NULL};//绝对路径 // execv("/bin/ls",argv); //从环境变量中查找某模块 **pexecvp("ls",argv);//execl("/bin/ls","ls","/",NULL);}//父子进程都会执行:子进程中ls替换了子进程的数据区和代码区int i=0,result=0;for(i=0;i<=100;i++){result+=i;} cout<<"1-100的和为:"<<result<<endl;cout<<"a.out进程执行完成啦\n"<<endl;return 0;
}
管道,创建一个 pipe(fd); 的管道,创建了一个子进程,先关闭 fd[0] (fd[0]管道的读操作) , 再在 write 中写入到管道 fd[1] (管道的写操作) , 再在子进程中 , 进行对管道 fd[0] 进行 read 操作 , 把写入到管道里的信息读取出来 .
#include<iostream>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
using namespace std;
int main()
{char str[100]="";
//1创建管道int fd[2];pipe(fd);
//两个进程int pid=fork();if(pid>0)//父进程输入信息到管道{strcpy(str,"123456789");//关闭读取close(fd[0]);//父亲写入信息到管道中write(fd[1],str,strlen(str));}else if(pid==0)//子进程读取父程序的内容{//关闭写端close(fd[1]);//子进程从管道中读取信息char ch;while(read(fd[0],&ch,1)>0)cout<<ch<<endl;}
}
实现简单的 shell 的命令 , 可以实现 a.out -l data.data 可以将data.data的文件信息读取出来 .
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
using namespace std;
int main()
{char title[]="[***********]$ ";char cmd[255]="";int pid;char* matter[100]={NULL};//100个地址int i=0;//父进程while(1){cout<<title;//输出标题gets(cmd);//输入(以\n 空格字符作为字符串的结符串)//创建子进程pid=fork();if(pid>0){//等待子进程结束wait(NULL);}else if(0==pid){ //解析字符串:matter[i]=strtok(cmd," ");while((matter[++i]=strtok(NULL," "))!=NULL);//替换子进程的信息execvp(matter[0],matter);}}return 0;
}

教室的那一间 我怎么看不见
消失的下雨天 我好想再淋一遍
《晴天》