exec实例详解

来源:互联网 发布:网络博客体验金 编辑:程序博客网 时间:2024/05/20 20:03

下面这个实例通过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将此参数设置为完全的路径名。