博客
这节课主要是对进程的进阶介绍,主要介绍的几个函数
1.exec函数组
exec:一个进程调用exec类函数,它本身就"死亡"了,系统把代码段替换成新的程序代码,废弃原有数据段和堆栈段,并为新程序分配新数据段与堆栈段
2.分类:
execl类:函数将以列举的形式传入参数,由于参数列表的长度不定,所以要用哨兵NULL表示列举结束;
execv类:函数将以参数向量表传递参数,char * argv[]的形式传递文件执行时使用的参数,数组中最后一个参数为NULL
#include <unistd.h>
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 execve(const char *path, char * const argv[], char * const envp[]);
//path表示的是文件的路径,file可以直接写作文件名
示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t tempPid;
tempPid=fork();
if(tempPid == -1){
perror("fork error");
exit(1);
} else if(tempPid > 0) {
printf("parent process:pid=%d\n", getpid());
} else {
printf("child process:pid=%d\n", getpid());
char *arg[]={"-a","-l","test_exec.c", NULL}; //通过指针定义功能
execvp("ls", arg);//使用该指针所指定的命令理出文件的信息
perror("error exec\n");
printf("child process:pid=%d\n", getpid());
} //of if
return 0;
} //of main
运行结果
关于特殊的进程“孤儿进程”和“僵尸进程”已经在上一篇讲过