l6-d2 exec函数族

一、exec函数族

exec函数族的功能:

        1.进程调用exec函数族执行某个程序

        2.进程当前内容被指定的程序替换

        3. 实现让父子进程执行不同的程序:

                1)父进程创建子进程

                2)子进程调用exec函数族

                父进程不受影响

1.execl、execlp

#include <unistd.h>

        int execl(const char *path, const char *arg, …);

        int execlp(const char *file, const char *arg, …);

        成功时执行指定的程序;失败时返回EOF

        path   执行的程序名称,需要包含路径

        arg…  传递给执行的程序的参数列表

        file   执行的程序的名称,在PATH中查找

代码演示:

#include <stdio.h>
#include <unistd.h>

int main(){
    pid_t pid;
    printf("before exec\n");
    pid = fork();
    if(pid==0){
        if(execl("/bin/ls","-a","-l","./",NULL)<0)    //显示目录下所有文件的详细信息
        {
		perror("execl");            //if(execlp("ls","ls","-a","-l","./",NULL)<0)
        }                           //perror("execlp");   
    }
   	printf("after execl\n");
}

 2.execv、execvp

#include <unistd.h>

        int execv(const char *path, char *const arg[]);

        int execvp(const char *file, char *const arg[]);

        成功时执行指定的程序;失败时返回EOF

        arg… 封装成指针数组的形式

代码演示:

#include <stdio.h>
#include <unistd.h>

int main(){
    pid_t pid;
    cahr *arg[] = {"ls","-a","-l","/etc",NULL}     //参数位于数组中
    printf("before exec\n");
    pid = fork();
    if(pid==0){
        if(execv("/bin/ls",arg)<0)    //显示目录下所有文件的详细信息
        {
		perror("execv");            //if(execvp("ls",arg)<0)
        }                           //perror("execvp");   
    }
   	printf("after execl\n");
}

3.system函数

#include <stdlib.h>

        int system(const char *command);

        成功时返回命令command的返回值;失败时返回EOF

        当前进程等待command执行结束后才继续执行

二、作业

用exec函数族函数实现 "ls -l -a" 命令

#include<stdio.h>
#include<unistd.h>
int main(){
	printf("before execl\n");
	if(execl("/bin/ls","ls","-l","-a",NULL) == -1){
		printf("execl filed\n");
		perror("execl\n");
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值