2015年2月3日 星期二

[C] How to use the function of execvp


#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  24 10:14 .
drwxr-xr-x 25 root    root    4.0K  120 10:36 ..
-rwxrwxr-x  1 freeman freeman 8.5K  24 10:14 a.out
srw-------  1 freeman freeman    0  24 09:43 fcitx-socket-:0
srw-------  1 freeman freeman    0  24 10:09 geany_socket.8881f632
-rw-rw-r--  1 freeman freeman  703  24 10:14 happy.c
-r--r--r--  1 root    root      11  24 09:42 .X0-lock
drwxrwxrwt  2 root    root    4.0K  24 09:42 .X11-unix


Reference:
Execute a Program: the execvp() System Call

0 意見:

張貼留言