系统级程序设计第三课
0x01 exec
exec:一个进程调用exec类函数,它本身就"死亡"了,系统把代码段替换成新的程序代码,废弃原有数据段和堆栈段,并为新程序分配新数据段与堆栈段
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[]);
使用exec函数可以用于命令执行
例如:
#include<unistd.h>
#include<stdlib.h>
int main()
{
char *arg[] = {"-a"};
pid_t p;
p=fork();
execvp("ls",arg);
}
可以执行ls等命令
0x02 exit
在exit封装内部有一个核心函数,_exit(),当遇到一个函数是以下划线开头,那么这个函数会更贴近于底层。那么exit()与_exit()有什么不同呢?
_exit:系统会无条件停止操作,终止进程并清除进程所用内存空间及进程在内核中的各种数据结构;
exit:对_exit进行了包装,在调用_exit()之前先检查文件的打开情况,将缓冲区中的内容写回文件。相对来说exit比_exit更为安全
0x03 进程通信
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int tempFd[2];
int tempRet = pipe(tempFd);
pid_t tempPid = fork();
if(tempPid > 0){//父进程—读
close(tempFd[1]);//关闭写端
char tempBuf[64]={0};
tempRet = read(tempFd[0], tempBuf, sizeof(tempBuf));//读数据
close(tempFd[0]);
write(STDOUT_FILENO, tempBuf, tempRet);//将读到的数据写到标准输出
wait(NULL);
} else if(tempPid == 0){//子进程—写
close(tempFd[0]);//关闭读端
char *tempStr="hello,pipe\n";
write(tempFd[1], tempStr, strlen(tempStr)+1);//写数据
close(tempFd[1]);
}
}
实现了子进程向管道写入数据,父进程读取数据