exec and get pid

exec is used for start another program in the c code of linux

1.execl

  1. int execl(const char*path,const char* arg,...)  

the last parameter must end up with NULL.

  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. int main()  
  4. {  
  5.     execl("/home/cascais/code/hello","hello","3",NULL);  
  6.     return 0;  
  7. }  

the path can be absolutely path or relative path like "./hello"

 

2.execlp

  1. <pre name="code" class="cpp">int execl(const char*path,const char* arg,...)  
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. int main()  
  4. {  
  5.     execlp("pwd","pwd",NULL);  
  6.     return 0;  
  7. }  

it won't work with execl. execl need the full path "/bin/pwd"

 

3.execv

  1. int execv(const char* path,const char* argv[])  

use string array instead of string list.

  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. int main()  
  4. {  
  5.     char* argv[] = {"ls" , "-al", NULL};  
  6.     execv("/bin/ls", argv);  
  7.     return 0;  
  8. }  

must has NULL


4.execv

  1. int execve(const char* path,const char* argv[], char * const evnp[]);  

 

  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3. int main()  
  4. {  
  5.     char* argv[] = {"echo" , "$PATH", NULL};  
  6.     char * evnp[]={"PATH=/bin",0};  
  7.     execve("/bin/echo", argv, evnp);  
  8.     return 0;  
  9. }  

it turns to be "$PATH" , not "/bin"

I havn't found what "evnp" is for.

 

5. ececvp

  1. int execv(const char* path,const char* argv[])  

like ececlp

but use argv instead of sting list.

  1. <pre name="code" class="cpp">#include <stdio.h>  
  2. #include <unistd.h>  
  3. int main()  
  4. {  
  5.     char* argv[] = {"ls" , "-al", NULL};  
  6.     execvp("ls", argv);  
  7.     return 0;  
  8. }  
  1. </pre><pre name="code" class="cpp" style="background-color: rgb(255, 255, 255); ">  
  1. </pre><pre name="code" class="cpp" style="background-color: rgb(255, 255, 255); "><pre>  
  1. #include <unistd.h>  
  2. #include <stdio.h>  
  3. #include <sys/syscall.h>  
  4. #include <unistd.h>  
  5.   
  6. #define gettid() ((pid_t) syscall(SYS_gettid))  
  7. int main()  
  8. {  
  9.     printf("start pid=%d,tid=%d\n", getpid(),gettid());  
  10.       

posted @ 2012-04-02 19:56  cascais  阅读(309)  评论(0编辑  收藏  举报