Linux下system函数调用的安全性和效率

system的原型定义大体如下:

    #include <stdio.h>
    #include <stddef.h>
    #include <signal.h>
    #include <unistd.h>
    #include <sys/wait.h>
    #include <sys/syscall.h>
    #if ! defined __NR_vfork
    #define vfork fork
    #endif

    int system(char *cmdstr)
    {
        int wait_state = -1;
        int  pid = -1;
        __sighandler_t save_quit;

        __sighandler_t save_int;

        __sighandler_t save_chld;

        if (NULL == cmdstr)
        {
             return 1;
        }

        save_quit = signal(SIGQUIT, SIG_IGN);
        save_int = signal(SIGINT, SIG_IGN);
        save_chld = signal(SIGCHLD, SIG_DFL);

        if ((pid = vfork()) < 0)
        {
             signal(SIGQUIT, save_quit);
             signal(SIGINT, save_int);
             signal(SIGCHLD, save_chld);
             return -1;
        }
       else if (0 == pid)
        {
            signal(SIGQUIT, SIG_DFL);
            signal(SIGINT, SIG_DFL);
            signal(SIGCHLD, SIG_DFL);

            execl("/bin/sh", "sh", "-c", cmdstr, (char *)0);
           _exit(127);
        }
 
        signal(SIGQUIT, SIG_IGN);
        signal(SIGINT, SIG_IGN);

        if (waitpid(pid, &wait_state, 0) == -1)
        {
            wait_state = -1;
        }

        signal(SIGQUIT, save_quit);
        signal(SIGINT, save_int);
        signal(SIGCHLD, save_chld);
        return wait_state;
    }

posted @ 2011-09-24 16:35  only_eVonne  阅读(2233)  评论(0编辑  收藏  举报