2014年5月31日 星期六

[C] Spawn

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int spawn(char *prog, char **arg_list)
{
    pid_t child;
    child = fork();
    if (child != 0)
    {
        return child;
    } else {
        execvp(prog,arg_list);
        fprintf(stderr,"spawn error\n");
        return -1;
    }
}

int main()
{
    int child_status;
    char *arg_list[] = {
        "ls",
        "-l",
        "/tmp",
        NULL
        };
    spawn("ls",arg_list);
    wait(&child_status);

    if(WIFEXITED(child_status))
        printf("child process exited normally, and its exit code is %d\n", WEXITSTATUS(child_status));
    else
        printf("child process exited abnormally\n");

    return 0;
}

Result :
total 12
srw------- 1 freeman freeman    0  5月 31 22:26 geany_socket.21900549
drwx------ 2 freeman freeman 4096  1月  1  1970 orbit-freeman
drwx------ 2 root    root    4096  5月 31 22:05 pulse-PKdhtXMmr18n
drwx------ 2 freeman freeman 4096  5月 31 22:05 ssh-vfnlXVpNsFd9
child process exited normally, and its exit code is 0

0 意見:

張貼留言