linux的system函数



linux的system函数
 
下面为system函数的一种实现:  www.2cto.com  
[cpp] 
#include <sys/wait.h>  
#include <errno.h>  
#include <unistd.h>  
  
int system(const char *cmdstring)  
{  
        pid_t   pid;  
        int     status;  
  
        if(cmdstring == NULL)      //system接受命令为空时直接返回  
                return(1);  
       
        if(pid = fork() < 0)       //fork一个子进程  
        {     
                status = -1;   
        }     
        else if(pid == 0)          //子进程启动一个程序来代替自己.  
        {     
                execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);  //调用shell,shell的路径是/bin/sh,剩下的为参数,-c选项告诉shell程序取下  
                _exit(127);                                          //一个命令行参数(在这里为cmdstring)作为命令输入.  
        }     
        else  
        {     
                while(waitpid(pid, &status, 0) < 0)     //父进程等待自进程结术.  
                {     
                        if(errno != EINTR)  
                        {     
                                status = -1;   
                                break;  
                        }     
                }     
        }     
        return(status);  
}  
其中子进程相当于调用: /bin/sh -c cmdstring-----------为执行cmdstring命令.
 

相关内容

    暂无相关文章