exec and get pid

Linux exec家族详解
本文详细介绍了Linux下用于启动新进程的exec家族函数,包括execl、execlp、execv、execve和execvp。解释了这些函数如何使用及它们之间的区别,并提供了具体的示例代码。

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.       

转载于:https://www.cnblogs.com/elfylin/archive/2012/04/02/2430240.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值