exec and get pid
exec is used for start another program in the c code of linux
1.execl
- int execl(const char*path,const char* arg,...)
the last parameter must end up with NULL.
- #include <stdio.h>
- #include <unistd.h>
- int main()
- {
- execl("/home/cascais/code/hello","hello","3",NULL);
- return 0;
- }
the path can be absolutely path or relative path like "./hello"
2.execlp
- <pre name="code" class="cpp">int execl(const char*path,const char* arg,...)
- #include <stdio.h>
- #include <unistd.h>
- int main()
- {
- execlp("pwd","pwd",NULL);
- return 0;
- }
it won't work with execl. execl need the full path "/bin/pwd"
3.execv
- int execv(const char* path,const char* argv[])
use string array instead of string list.
- #include <stdio.h>
- #include <unistd.h>
- int main()
- {
- char* argv[] = {"ls" , "-al", NULL};
- execv("/bin/ls", argv);
- return 0;
- }
must has NULL
4.execv
- int execve(const char* path,const char* argv[], char * const evnp[]);
- #include <stdio.h>
- #include <unistd.h>
- int main()
- {
- char* argv[] = {"echo" , "$PATH", NULL};
- char * evnp[]={"PATH=/bin",0};
- execve("/bin/echo", argv, evnp);
- return 0;
- }
it turns to be "$PATH" , not "/bin"
I havn't found what "evnp" is for.
5. ececvp
- int execv(const char* path,const char* argv[])
like ececlp
but use argv instead of sting list.
- <pre name="code" class="cpp">#include <stdio.h>
- #include <unistd.h>
- int main()
- {
- char* argv[] = {"ls" , "-al", NULL};
- execvp("ls", argv);
- return 0;
- }
- </pre><pre name="code" class="cpp" style="background-color: rgb(255, 255, 255); ">
- </pre><pre name="code" class="cpp" style="background-color: rgb(255, 255, 255); "><pre>
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/syscall.h>
- #include <unistd.h>
- #define gettid() ((pid_t) syscall(SYS_gettid))
- int main()
- {
- printf("start pid=%d,tid=%d\n", getpid(),gettid());
- }