【无标题】

系统级程序设计第三课

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]);
    }
}

实现了子进程向管道写入数据,父进程读取数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值