exec函数族的应用

#include <unistd.h>

extern char **environ;

int execl(const char *pathname, const char *arg, ...

          /* (char  *) NULL */);

int execlp(const char *file, const char *arg, ...

           /* (char  *) NULL */);

int execle(const char *pathname, const char *arg, ...

           /*, (char *) NULL, char *const envp[] */);

int execv(const char *pathname, char *const argv[]);

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

int execvpe(const char *file, char *const argv[],

            char *const envp[]);

例子:代码如下

char *argv1[] = {"./hello", NULL};

char *argv2[] = {"ls", "-l", NULL};

//if (0 > execl("./hello", "./hello", NULL))

//if (0 > execl("/usr/bin/ls", "ls", "-l", NULL))

//if (0 > execlp("ls", "ls", "-l", NULL))

//if (0 > execv("./hello", argv1))

if (0 > execvp("ls", argv2))

{

perror("exec");

return -1;

}

//printf("nihao!\n");

-----------------------------------------------------------------------------------------------------

代码2:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])

    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork");
        return -1;
    }
    if (0 == pid) //child
    {
        char *argv1[] = {"./hello", NULL};
        char *argv2[] = {"ls", "-l", NULL};
        //if (0 > execl("./hello", "./hello", NULL))
        //if (0 > execl("/usr/bin/ls", "ls", "-l", NULL))
        //if (0 > execlp("ls", "ls", "-l", NULL))
        //if (0 > execv("./hello", argv1))
        if (0 > execvp("ls", argv2))
        {
            perror("exec");
            return -1;
        }
        //printf("nihao!\n");
    }
    else
    {
        while (1)
        {
            printf("hello world!\n");
            sleep(1);
        }
    }


    return 0;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
exec 是 C 语言中的一个系统调用函数exec 函数),它们用于在进程中执行其他程序。exec 函数的一些常用函数包括 execl、execle、execv、execvp 等。 这些函数用于将当前进程替换为另一个可执行程序,并在新程序中执行指定的命令。使用 exec 函数可以方便地实现程序的动态执行和进程间的数据传递。 其中,execl 函数execle 函数需要手动传入待执行程序的路径和参数,使用空格分隔参数。execv 函数execvp 函数则需要将参数打包成一个数组,并传入参数数组的首地址。 exec 函数的原理是通过加载指定的可执行程序替换当前进程的代码段、数据段、堆栈等信息,使得当前进程执行其他程序。被替换的当前进程会完全消失,新的程序会从 main 函数开始执行。 exec 函数在操作系统中具有广泛的应用,常用于实现 shell 的内置命令,比如在 Linux 中使用 exec 函数来执行 shell 的 "ls"、"cd" 等命令。此外,exec 函数还常用于多进程编程中,通过创建子进程并执行其他程序,实现进程间的任务分工和协作。 总之,exec 函数是 C 语言中用于执行其他程序的一组函数。它们通过替换当前进程的代码段和数据段,实现了在进程中执行其他程序的功能。这些函数在操作系统中广泛使用,对于实现动态执行程序和进程间数据传递非常有用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

এ᭄星辰

混口饭吃。。。。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值