Linux 进程管理
1、进程操作
1.1 进程号
每个进程都由一个进程号来标识,其类型为 pid_t(整型),进程号的范围:0~32767。进程号总是唯一的,但进程号可以重用。当一个进程终止后,其进程号就可以再次使用。
进程号(PID):
标识进程的一个非负整型数。
父进程号(PPID):
任何进程( 除 init 进程)都是由另一个进程创建,该进程称为被创建进程的父进程,对应的进程号称为父进程号(PPID)。如,A 进程创建了 B 进程,A 的进程号就是 B 进程的父进程号。
进程组号(PGID):
进程组是一个或多个进程的集合。他们之间相互关联,进程组可以接收同一终端的各种信号,关联的进程有一个进程组号(PGID) 。这个过程有点类似于 QQ 群,组相当于 QQ 群,各个进程相当于各个好友,把各个好友都拉入这个 QQ 群里,主要是方便管理,特别是通知某些事时,只要在群里吼一声,所有人都收到,简单粗暴。但是,这个进程组号和 QQ 群号是有点区别的,默认的情况下,当前的进程号会当做当前的进程组号。
1.2 进程命令(ps)
- 可使用
ps
指令或者使用top
指令查看linux系统进程,实际工作中,配合grep
来查找程序中是否存在某一个进程。 - 每个进程都有一个非负整数表示的唯一 ID,叫做 pid ,类似身份证。
- 编程调用 getpid 函数获取自身的进程标识符,getppid 获取父进程的进程标识符。
- Pid=0: 称为交换进程( swapper )作用:进程调度。Pid=1 : init 进程,作用:系统初始化。
- 进程 A 创建了进程 B,那么 A 叫做父进程, B 叫做子进程,父子进程是相对的概念,理解为人类中的父子关系。
- 进程查找(ps -aux | grep 可执行文件名)
- 进程杀死 (kill -9 进程号)
2、进程创建
2.1 创建子进程 (fork 函数)
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
功能:
用于从一个已存在的进程中创建一个新进程,新进程称为子进程,原进程称为父进程。它与父进程 同时运行(并发),且运行顺序不定(异步)。
参数:
无
返回值:
成功:子进程中返回 0,父进程中返回子进程 ID。pid_t,为整型。
失败:返回-1。
失败的两个主要原因是:
1)当前的进程数已经达到了系统规定的上限,这时 errno 的值被设置为 EAGAIN。
2)系统内存不足,这时 errno 的值被设置为 ENOMEM
(pid_t 是一个宏定义,其实质是int, 被定义在#includesys/types.h>中)
-
返回值:若成功调用一次则返回两个值,子进程返回0,父进程返回子进程ID;否则,出错返回-1.
-
fork()函数调用的一个奇妙之处就是它仅仅被调用一次,却能够返回两次,一共有三种不同的返回值:
(1)在父进程中,fork返回新创建子进程的进程ID;
(2)在子进程中,fork返回0;
(3)如果出现错误,fork返回一个负值。
注: fork 调用生成的新进程与其父进程谁先执行不一定,哪个进程先执行要看系统的进程调度策略
区分父子进程1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if (pid < 0)
{ // 没有创建成功
perror("fork");
return 0;
}
if (0 == pid)
{ // 子进程
while (1)
{
printf("I am son\n");
sleep(1);
}
}
else if (pid > 0)
{ // 父进程
while (1)
{
printf("I am father\n");
sleep(1);
}
}
return 0;
}
运行结果:
通过运行结果,可以看到,父子进程各做一件事(各自打印一句话)。这里,我们只是看到只有一份代码,实际上,fork() 以后,有两个地址空间在独立运行着,有点类似于有两个独立的程序(父子进程)在运行着。
一般来说,在 fork() 之后是父进程先执行还是子进程先执行是不确定的。这取决于内核所使用的调度算法。
需要注意的是,在子进程的地址空间里,子进程是从 fork() 这个函数后才开始执行代码
区分父子进程2
举例说明 代码1:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t fpid; //fpid表示fork函数返回的值
int count = 0;
fpid = fork();
//如果出现错误,fork返回一个负值如果出现错误,fork返回一个负值
if (fpid < 0)
printf("error in fork!");
//在子进程中,fork返回0;
else if (fpid == 0)
{
printf("i am the child process, my process id is %d/n", getpid());
printf("我是爹的儿子/n");//对某些人来说中文看着更直白。
count++;
}
else {
printf("i am the father process, my process id is %d/n", getpid());
printf("我是孩子他爹/n");
count++;
}
printf("统计结果是: %d/n", count);
return 0;
}
运行结果:
区分父子进程3
代码2:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("father: id=%d\n",getpid());
pid = fork();//创建一个子进程
if(pid<0)//如果出现错误,fork返回一个负值如果出现错误,fork返回一个负值
{
printf("error in fork!");
}
else if(pid == 0)//在子进程中,fork返回0;
{
printf("this is child print,child pid = %d\n",getpid());
}
else if(pid > 0)//
{
printf("this is father print, pid = %d\n",getpid());
}
return 0;
}
运行结果
选择操作执行父、子进程
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int data = 10;
while(1)
{
printf("please input a data\n");
scanf("%d",&data);
if(data == 1)
{
pid = fork();//创建进程
if(pid > 0)
{
//父进程
printf("this is father print, pid = %d\n",getpid());
}
else if(pid == 0)
{
//子进程
while(1)
{
printf("this is child print,child pid = %d\n",getpid());
sleep(3);
}
}
}
else
{
printf("wait ,do nothing\n");
}
}
return 0;
}
- 创建子进程:
pid_t fork(void);
pid_t为int类型,进行了重载;
获得进程ID:pid_t getpid(void);
获得父进程ID:pid_t getppid(void);
2.2 获取进程号
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid, ppid, pgid;
pid = getpid();//获取本进程ID
printf("本进程号:pid = %d\n", pid);
ppid = getppid();//获得父进程ID
printf("父进程号:ppid = %d\n", ppid);
pgid = getpgid(pid);//获取进程组号
printf("进程组号:pgid = %d\n", pgid);
return 0;
}
运行结果:
- 用于创建一个进程,所创建的进程复制了父进程的 - 代码段/数据段/BSS段/堆/栈等所有用户空间信息- 在内核中操作系统重新为其申请了一个PCB,并使用父进程的PCB进行初始化。
代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//打印结果:父进程和子进程交替打印
int main()
{
pid_t pid;
pid = fork();
if(pid > 0)
{
while(1)
{
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else
if(pid == 0)
{
while(1)
{
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
}
}
return 0;
}
运行结果:父进程和子进程交替打印
2.3 vfork函数 (子进程先运行)
vfork 函数 也可以创建进程
1)vfork 直接使用父进程存储空间,不拷贝。
2)vfork 保证子进程先运行 , 当子进程调用 exit 退出后,父进程才执行。
vfork( ) 函数功能实验1
代码示例: vfork 保证子进程先运行
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//使用vfork()函数,打印结果为:一直打印子进程,vfork 保证子进程先运行。
int main()
{
pid_t pid;
pid = vfork();
if(pid > 0)
{
while(1)
{
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)
{
while(1)
{
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
}
}
return 0;
}
运行结果:一直打印子进程,vfork 保证子进程先运行
vfork() 函数功能实验2
代码示例: 子进程调用 exit 退出后,父进程才执行
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
//当子进程调用 exit 退出后,父进程才执行
int main()
{
pid_t pid;
int cont=0;
pid = vfork(); //
if(pid > 0)
{
while(1)
{
printf("cout=%d\n",cont);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)
{
while(1)
{
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cont++;
if(cont==3)
{
exit(0);//推荐此方法正常退出
//break;
}
}
}
return 0;
}
运行结果:先执行子进程,然后执行父进程
3、进程退出(exit 函数)
1) . Main 函数调用 return
2). 进程调用 exit(), 标准 c 库
3). 进程调用 _exit() 或者 _Exit() ,属于系统调用
3.1 等待子进程退出函数
- wait() 和 waitpid() 函数的功能一样,区别在于,wait() 函数会阻塞,waitpid() 可以设置不阻塞,waitpid() 还可以指定等待哪个子进程结束。
- 注意:一次wait或waitpid调用只能清理一个子进程,清理多个子进程应使用循环。
3.1.1 wait函数 (会阻塞)
父进程会阻塞,等待子进程结束后(才开始执行)继续执行。
函数说明:wait() 函数会阻塞
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
功能:
等待任意一个子进程结束,如果任意一个子进程结束了,此函数会回收该子进程的资源。
参数:
status : 进程退出时的状态信息。
返回值:
成功:已经结束子进程的进程号
失败: -1
-
调用 wait() 函数的进程会挂起(阻塞),直到它的一个子进程退出或收到一个不能被忽视的信号时才被唤醒(相当于继续往下执行)。
(意思是父进程会一致等待 (阻塞),等待子进程结束后(才开始执行)继续执行) -
若调用进程没有子进程,该函数立即返回;若它的子进程已经结束,该函数同样会立即返回,并且会回收那个早已结束进程的资源。
所以,wait()函数的主要功能为回收已经结束子进程的资源。
wait()函数功能1
代码1:wait()函数值为空值
如没有调用wait()函数父子进程会交替执行输出打印,调用wait函数后,父进程会阻塞这里,子进程运行;等子进程退出以后父进程才会继续往下执行。
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//如没有调用wait函数父子进程会交替执行
//调用wait函数,父进程会阻塞这里子进程退出以后父进程继续往下执行
int main()
{
pid_t pid;
int cnt = 0;
pid = fork();//父子进程会交替打印
if(pid > 0)
{
//调用wait函数,父进程会阻塞这里子进程退出以后父进程继续往下执行
wait(NULL);//wait为空值时
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)
{
while(1)
{
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){//打印3次后子进程退出收回
exit(0);
}
}
}
return 0;
}
运行结果:
不用wait()函数的打印结果:
3. 如果参数 status 的值不是 NULL,wait() 就会把子进程退出时的状态取出并存入其中,这是一个整数值(int),指出了子进程是正常退出还是被非正常结束的。
- 这个退出信息在一个 int 中包含了多个字段,直接使用这个值是没有意义的,我们需要用宏定义取出其中的每个字段。
宏函数可分为如下三组:
1、 WIFEXITED(status)
为非0 → 进程正常结束
WEXITSTATUS(status):获取进程退出状态 (exit的参数)
如上宏为真,使用此宏 → 获取进程退出状态 (exit的参数)
2、WIFSIGNALED(status)
为非0 → 进程异常终止
WTERMSIG(status)
如上宏为真,使用此宏 → 取得使进程终止的那个信号的编号。
3、WIFSTOPPED(status)
为非0 → 进程处于暂停状态
WSTOPSIG(status)
如上宏为真,使用此宏 → 取得使进程暂停的那个信号的编号。
WIFCONTINUED(status)
为真 → 进程暂停后已经继续运行
wait()函数功能1
代码2:wait()函数值不为空,取出退出时的状态
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//wait不为空值时
int main()
{
pid_t pid;
int cnt=0;
int status=10;
pid = fork();//父子进程会交替打印
if(pid > 0)
{
wait(&status);//父进程阻塞
printf("child quit,child status=%d\n",WEXITSTATUS(status));//WEXITSTATUS(status):获取进程退出状态 (exit的参数)
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){
exit(5);//设置进程退出状态返回值为5
}
}
}
return 0;
}
运行结果:子进程先运行,并打印3次,然后返回结束状态(设置的是5)然后父进程运行;父进程先打印子进程结束的状态(5),然后打印。
子进程返回的结束状态可以设置不同的数值。这里我们设置的是5。
3.1.2 waitpid函数(不会阻塞)
不阻塞的情况下,waitpid() 还可以指定等待哪个子进程结束。
函数说明:waitpid() 可以设置不阻塞,waitpid() 还可以指定等待哪个子进程结束
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
功能:
等待子进程终止,如果子进程终止了,此函数会回收子进程的资源。
参数:
pid = fork()子进程中返回 0,父进程中返回子进程 ID,失败返回-1
pid : 参数 pid 的值有以下几种类型(进程ID号)
pid > 0 等待进程 ID 等于 pid 的子进程。
pid = 0 等待同一个进程组中的任何子进程,如果子进程已经加入了别的进程组,waitpid 不会等待它。
pid = -1 等待任一子进程,此时 waitpid 和 wait 作用一样。
pid < -1 等待指定进程组中的任何子进程,这个进程组的 ID 等于 pid 的绝对值。
status : 进程退出时的状态信息。和 wait() 用法一样。(子进程返回的结束信息)
options : options 提供了一些额外的选项来控制 waitpid()。
0:同 wait(),阻塞父进程,等待子进程退出。
WNOHANG:没有任何已经结束的子进程,则立即返回。
WUNTRACED:如果子进程暂停了则此函数马上返回,并且不予以理会子进程的结束状态。(由于涉及到一些跟踪调试方面的知识,加之极少用到)
返回值:(返回值如果小于0子进程全部退出了;大于0表示回收到了子进程; =0没有进程没有退出)
waitpid() 的返回值比 wait() 稍微复杂一些,一共有 3 种情况:
1) 当正常返回的时候,waitpid() 返回收集到的已经回收子进程的进程号;
2) 如果设置了选项 WNOHANG,而调用中 waitpid() 发现没有已退出的子进程可等待,则返回 0;
3) 如果调用中出错,则返回-1,这时 errno 会被设置成相应的值以指示错误所在,如:当 pid 所对应的子进程不存在,或此进程存在,但不是调用进程的子进程,waitpid() 就会出错返回,这时 errno 被设置为 ECHILD;
waitpid函数功能
代码示例:
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//wait为空值时
int main()
{
pid_t pid;
int cnt=0;
int status=10;
pid = fork();//父子进程会交替打印
if(pid > 0)
{
// wait(&status);
waitpid(pid,&status,WNOHANG);
printf("child quit,child status=%d\n",WEXITSTATUS(status));//WEXITSTATUS(status):获取进程退出状态 (exit的参数)
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){
exit(5);//设置返回值为5
}
}
}
return 0;
}
运行结果:情况1:waitpid(pid,&status,WNOHANG),第三个参数是WNOHANG
情况2:waitpid(pid,&status,0),第三个参数是0;等同于同 wait()函数
3.2 僵尸进程
子进程终止,父进程尚未回收,子进程退出状态没有被收集,就会变成僵死进程。如(2.3中vfork() 函数功能实验2: 子进程调用 exit 退出后,父进程才执)此代码子进程退出后,父进程没有收集子进程的状态,这时候子进程状态就变成僵死进程。
- 父进程可以通过调用wait或waitpid得到它的退出状态同时彻底清除掉这个进程。
3.3 孤儿进程
父进程运行结束,但子进程还在运行(未运行结束)的子进程就称为孤儿进程(Orphan Process)。
每当出现一个孤儿进程的时候,内核就把孤儿进程的父进程设置为 init ,而 init 进程会循环地 wait() 它的已经退出的子进程。这样,当一个孤儿进程凄凉地结束了其生命周期的时候,init 进程就会代表党和政府出面处理它的一切善后工作。
(Linux 避免系统存在过多孤儿进程, init 进程收孤儿进程,变成孤儿进程的父进程)
孤儿进程实验代码
示例代码:父进程执行一次后退出
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = fork();
if(pid > 0)
{
//父进程
printf("this is father print, pid = %d\n",getpid());
}
//子进程
else if(pid == 0)
{
while(1)
{
printf("this is chilid print, pid = %d,my father pid=%d\n",getpid(),getppid());
sleep(1);
cnt++;
if(cnt == 5)//执行5次
{
exit(3);
}
}
}
return 0;
}
运行结果:
4、进程替换
在 Windows 平台下,我们可以通过双击运行可执行程序,让这个可执行程序成为一个进程;而在 Linux 平台,我们可以通过 ./
运行,让一个可执行程序成为一个进程。
- exec族函数函数的作用:
-
我们用fork函数创建新进程后,经常会在新进程中调用exec函数去执行另外一个程序。当进程调用exec函数时,该进程被完全替换为新程序。因为调用exec函数并不创建新进程,所以前后进程的ID并没有改变。
-
exec 函数族的作用是根据指定的文件名或目录名找到可执行文件,并用它来取代调用进程的内容,换句话说,就是在调用进程内部执行一个可执行文件。
-
进程调用一种 exec 函数时,该进程完全由新程序替换,而新程序则从其 main 函数开始执行。因为调用 exec 并不创建新进程,所以前后的进程 ID (当然还有父进程号、进程组号、当前工作目录……)并未改变。exec 只是用另一个新程序替换了当前进程的正文、数据、堆和栈段(进程替换)。
- 函数族:
exec函数族分别是:execl, execlp, execle, execv, execvp, execvpe
函数原型:
#include <unistd.h>
extern char **environ;
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[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);
-
返回值:
exec函数族的函数执行成功后不会返回,调用失败时,会设置errno并返回-1,然后从原程序的调用点接着往下执行。 -
参数说明:
path:可执行文件的路径名字
arg:可执行程序所带的参数,第一个参数为可执行文件名字,没有带路径且arg必须以NULL结束
file:如果参数file中包含/,则就将其视为路径名,否则就按 PATH环境变量,在它所指定的各目录中搜寻可执行文件。 -
exec族函数参数极难记忆和分辨,函数名中的字符会给我们一些帮助:
l : 使用参数列表
p:使用文件名,并从PATH环境进行寻找可执行文件
v:应先构造一个指向各参数的指针数组,然后将该数组的地址作为这些函数的参数。
e:多了envp[]数组,使用新的环境变量代替调用进程的环境变量
4.1 exec函数使用
4.2 带 l 的一类exac函数
(l表示list),包括execl、execlp、execle,要求将新程序的每个命令行参数都说明为 一个单独的参数。这种参数表以空指针结尾。
以execl函数为例子来说明:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("before execl\n");
//如果没有创建echoarg文件会调用失败
//./echoarg:文件路径,echoarg:文件名 , abc:参数
//参数结尾必须用NULL做结尾。。
if(execl("./echoarg","echoarg","abc",NULL) == -1)
{
printf("execl failed!\n"); //调用失败时,会设置errno并返回-1,然后从原程序的调用点接着往下执行。
perror("why");//打印错误原因
}
printf("after execl\n");
return 0;
}
运行失败的-运行结果:
运行成功时-运行结果:
- 首先创建echoarg.c文件,然后编译输出可执行文件echoarg,然后运行上面的程序。
//文件echoarg.c
#include <stdio.h>
int main(int argc,char *argv[])
{
int i = 0;
for(i = 0; i < argc; i++)
{
printf("argv[%d]: %s\n",i,argv[i]);
}
return 0;
}
最后运行结果:
实验说明:
我们先用gcc编译echoarg.c,生成可执行文件echoarg并放在当前路径目录下。文件echoarg的作用是打印命令行参数。然后再编译execl.c并执行execl可执行文件(a.out)。用execl 找到并执行echoarg,将当前进程main替换掉,所以”after execl” 没有在终端被打印出来。
示例代码:调用ls命令
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("before execl\n");
if(execl("/bin/ls","ls",NULL,NULL) == -1)//
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
运行结果:
示例代码:调用ls命令,并传参。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("before execl\n");
if(execl("/bin/ls","ls","-l",NULL) == -1)//调用ls 并传 -l
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
运行结果:
代码示例:获取系统时间:
首先确定date命令所在路径:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("this pro get system date:\n");
if(execl("/bin/date","date",NULL,NULL) == -1)//date 的文件路径
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
运行结果:
4.3 带 p 的一类exac函数
包括execlp、execvp、execvpe,如果参数file中包含/,则就将其视为路径名,否则就按 PATH环境变量,在它所指定的各目录中搜寻可执行文件。举个例子,PATH=/bin:/usr/bin
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("this pro get system date:\n");
if(execl("date","date",NULL,NULL) == -1)//参数没有带路径,会执行错误
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
上面这个例子因为参数没有带路径,所以execl找不到可执行文件。
下面再看一个例子对比一下:
如果我们把execl()
函数改成execlp()
函数,运行成功。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("this pro get system date:\n");
if(execlp("date","date",NULL,NULL) == -1)//参数没有带路径,执行成功
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
从上面的实验结果可以看出,上面的exaclp函数带p,所以能通过环境变量PATH查找到可执行文件date。
4.4 带 v 不带l的一类exac函数
包括execv、execvp、execve,应先构造一个指向各参数的指针数组,然后将该数组的地址作为这些函数的参数。
如char *arg[]这种形式,且arg最后一个元素必须是NULL,例如char *arg[] = {“ls”,”-l”,NULL};
下面以execvp函数为例说明:
示例代码:把execvp()函数参数定义一个数组
//文件execvp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execvp(const char *file, char *const argv[]);
int main(void)
{
printf("before execlp****\n");
char *argv[] = {"ls","-l",NULL};//把参数定义一个数组
if(execvp("ls",argv) == -1)
{
printf("execvp failed!\n");
}
printf("after execlp*****\n");
return 0;
}
运行结果:
4.5 带 e 的一类exac函数
包括execle、execvpe,可以传递一个指向环境字符串指针数组的指针。 参数例如char *env_init[] = {“AA=aa”,”BB=bb”,NULL}
; 带e表示该函数取envp[]数组,而不使用当前环境。
下面以execle函数为例:
示例代码:
//文件execle.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execle(const char *path, const char *arg,..., char * const envp[]);
char *env_init[] = {"AA=aa","BB=bb",NULL};
int main(void)
{
printf("before execle****\n");
if(execle("./echoenv","echoenv",NULL,env_init) == -1)
{
printf("execle failed!\n");
}
printf("after execle*****\n");
return 0;
}
//文件echoenv.c
#include <stdio.h>
#include <unistd.h>
extern char** environ;
int main(int argc , char *argv[])
{
int i;
char **ptr;
for(ptr = environ;*ptr != 0; ptr++)
printf("%s\n",*ptr);
return 0;
}
我们先写一个显示全部环境表的程序,命名为echoenv.c,然后编译成可执行文件放到当前目录下。然后再运行可执行文件execle,发现我们设置的环境变量确实有传进来。
运行结果:
5、system()函数
函数原型:int system(const char * command)
包含在头文件 “stdlib.h” 中。
函数返回值:命令执行成功返回0,执行失败返回-1。
功能举例:
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
char ret[1024] = {0};
system("ls");
printf("ret=%s\n",ret);
return 0;
}
6、popen()函数
头文件:#include <stdio.h>
函数原型:FILE popen( const char command, const char* mode )
比 system 在应用中的好处:可以获取运行的输出结果!
返回值:
如果调用成功,则返回一个读或者打开文件的指针,如果失败,返回NULL,具体错误要根据errno判断。
int pclose (FILE* stream)
参数说明:
stream:popen返回的文件指针
返回值:
如果调用失败,返回 -1
popen() 函数用于创建一个管道:其内部实现为调用 fork 产生一个子进程,
执行一个 shell 以运行命令来开启一个进程这个进程必须由 pclose() 函数关闭。
功能示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
int main(void)
{
char ret[1024] = {0};
FILE *fp;
fp = popen("ls","r");//popen执行完后,读取内容
int nread = fread(ret,1,1024,fp); //把读取的内容返回到ret数组中
printf("read ret %d byte, ret=%s\n",nread,ret);//打印结果ret中的数据
return 0;
}
运行结果:
例子一:popen执行完后,读取内容
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp = NULL;
char buf[10240] = {0};
fp = popen("ls -al","r");
if(fp == NULL){
return 0;
}
fread(buf, 10240, 1, fp);
printf("%s\n",buf);
pclose(fp);
return 0;
}
例子二
popen执行完后,仍然可以向管道继续传送命令,实现功能
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp = NULL;
char buf[10240] = {0};
fp = popen("mysql -u root -p123456 my_db","w");
if(fp == NULL){
return 0;
}
fprintf(fp,"delete from my_test_table;");
fprintf(fp,"\\q");
pclose(fp);
return 0;
}