#include<stdio.h>
#include<sys/types.h>
#define LS_PATH "/tmp"
int main()
{
int counter = 0;
char *argv[10];
argv[counter++] = "ls";
argv[counter++] = "-a";
argv[counter++] = "-l";
argv[counter++] = "-h";
argv[counter] = NULL;
pid_t pid;
if((pid=fork()) == -1)
{
printf("Failed forking for TFTP");
return -1;
}
if(pid == 0)
{
/*Child process*/
chdir(LS_PATH);
if(execvp(*argv, (char** const)argv) == -1)
{
printf("Executing ls ERROR");
return -1;
}
}
else
{
/*Parent process*/
return pid;
}
return 0;
}
Result :
./a.out
drwxrwxrwt 8 root root 4.0K 2月 4 10:14 .
drwxr-xr-x 25 root root 4.0K 1月 20 10:36 ..
-rwxrwxr-x 1 freeman freeman 8.5K 2月 4 10:14 a.out
srw------- 1 freeman freeman 0 2月 4 09:43 fcitx-socket-:0
srw------- 1 freeman freeman 0 2月 4 10:09 geany_socket.8881f632
-rw-rw-r-- 1 freeman freeman 703 2月 4 10:14 happy.c
-r--r--r-- 1 root root 11 2月 4 09:42 .X0-lock
drwxrwxrwt 2 root root 4.0K 2月 4 09:42 .X11-unix
Reference:
Execute a Program: the execvp() System Call
0 意見:
張貼留言