exec
exec
: execve
, execl
, execlp
, โฆ.exec
ํจ์๋ ์ธ์๋ก ๋ฐ์ ๋ค๋ฅธ ํ๋ก๊ทธ๋จ์ ์์ ์ ํธ์ถํ ํ๋ก์ธ์ค์ ๋ฉ๋ชจ๋ฆฌ์ ๋ฎ์ด์ด๋ค. ๋ฐ๋ผ์ ํ๋ก์ธ์ค๊ฐ ์ํ ์ค์ด๋ ๊ธฐ์กด ํ๋ก๊ทธ๋จ์ ์ค์ง๋์ด ์์ด์ง๊ณ , ์๋ก ๋ฎ์ด์ด ํ๋ก๊ทธ๋จ์ด ์คํ๋๋ค. exec ํจ์๊ตฐ์ ํธ์ถํ ํ๋ก์ธ์ค ์์ฒด๊ฐ ๋ฐ๋๋ฏ๋ก, exec ํจ์๋ฅผ ํธ์ถํด ์ฑ๊ณตํ๋ฉด ๋ฆฌํด๊ฐ์ด ์์ต๋๋ค.
๋น์ทํ ๊ธฐ๋ฅ์ ํ๋ fork
๋ ํ๋ก์ธ์ค๋ฅผ ๋ณต์ ํ๊ณ , exec
์ ํ๋ก์ธ์ค๋ฅผ ๋์ฒดํ๋ค.
exec
์ ์๊ณ ๋ฆฌ์ฆexecve
y=execve(fname, argv, envp); // change to fname with additional arguments specified in argv[]
// and additional environment variables specified in envp[].
// returns -1 if error.
y=execve("/aa/bb", k, 0); // change to /aa/bb with additional arguments in k
ex1.c:
#include <stdio.h>
int main(){
printf("I am ex1\n");
}
ex2.c:
#include <stdio.h>
#include <unistd.h>
int main(){
execve("./ex1",0 , 0); // change to ./ex1 with no additional argument
printf("I am ex2\n");
}
$ gcc -o ex1 ex1.c
$ gcc -o ex2 ex2.c
$ ex2
I am ex1
execve(const char *filename, char *const argv[], char *const envp[]);
execve
ํจ์๋ ์คํ๊ฐ๋ฅํ ํ์ผ์ธ filename์ ์คํ์ฝ๋๋ฅผ ํ์ฌ ํ๋ก์ธ์ค์ ์ ์ฌํ์ฌ ๊ธฐ์กด์ ์คํ์ฝ๋์ ๊ต์ฒดํ์ฌ ์๋ก์ด ๊ธฐ๋ฅ์ผ๋ก ์คํํ๋ค. ์ฆ, ํ์ฌ ์คํ๋๋ ํ๋ก๊ทธ๋จ์ ๊ธฐ๋ฅ์ ์์ด์ง๊ณ filename ํ๋ก๊ทธ๋จ์ ๋ฉ๋ชจ๋ฆฌ์ loadingํ์ฌ ์ฒ์๋ถํฐ ์คํํ๊ธฐ ๋๋ฌธ์ ex2๋ฅผ ์คํํ์ง๋ง ex1์ด ์คํ๋์๋ค.myexec.c:
#include <stdio.h>
int main(){
char *k[10];
k[0]="/bin/ls";
k[1]=0;
execve(k[0], k, 0); // change to /bin/ls with no additional argument
}
The above program will exec to /bin/ls and print the listing of files in the current directoy.
myexec.c:
int main(){
char *x[10];
x[0]="/bin/cat";
x[1]="f1";
x[2]=0; // argument list should end with 0
execve(x[0], x, 0); // change to /bin/cat with one argument f1
}
The above program will exec to โ/bin/cat f1โ which will print the contents of f1.
$ myexec
command> /bin/cat f1
myexec execs to โ/bin/cat f1โ
$ myexec
command> /bin/cp f1 f2
myexec execs to โ/bin/cp f1 f2โ
to avoid system-down, use a fixed-iteration loop:
for(;;){โฆ}
->for(i=0;i<5;i++){โฆ}
$ myexec
command> /bin/cat f1 // display the contents of f1
command> /bin/ls // display file names in the current directory
...
$
as follows. You may need โgetcwdโ.$ myexec
[/home/sp1/12345]$ /bin/cat f1 // display the contents of f1
[/home/sp1/12345]$ /bin/ls // display file names in the current directory
...