exec实例详解

下面这个实例通过execle调用了ls命令;

通过execlp调用了echo命令;

#include<sys/types.h>

#include<sys/wait.h>

#include"ourhdr.h"

 

//

char*env_init[] = {"USER=unknown","PATH=/tmp",NULL} ;

 

intmain()

{

    pid_t pid ;

   

    if( (pid = fork()) < 0 )

    {

        printf("fork error!\n");   

    }

    else if( 0 == pid )

    {

        //child

       if(execle("/bin/ls","ls","/home/huangxw",(char*)0,env_init) < 0)

        {

            printf("execleerror!\n");

            exit(-1);  

        }

    }

    else

    {

        //parent

        if( waitpid(pid, NULL , 0 ) < 0)

        {

            printf("waitpiderror!\n");

        }

    }

   //

    if( (pid = fork()) < 0 )

    {

        printf("fork error!\n");   

    }

    else if( 0 == pid )

    {

        //child

        //

       if(execlp("echo","echo","only_1_arg",(char*)0)< 0)

        {

            printf("execlperror!\n");

            exit(-1);

        }

    }

    exit(0);   

}

execle,它要求一个路径名和一个特定的环境。

execlp,它用一个文件名,并将调用者的环境传送给新程序execlp在这里能够工作的原因是因为目录/home/stevens/bin是当前路径前缀之一。

注意,我们将第一个参数(新程序中的argv[0])设置为路径名的文件名分量。某些shell将此参数设置为完全的路径名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值