Chinaunix首页 | 论坛 | 博客
  • 博客访问: 828383
  • 博文数量: 190
  • 博客积分: 2991
  • 博客等级: 少校
  • 技术积分: 2400
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-24 18:11
文章分类

全部博文(190)

文章存档

2015年(3)

2014年(1)

2013年(65)

2012年(121)

我的朋友

分类:

2012-12-01 11:00:31

下面为system函数的一种实现:
 
#include  
#include  
#include  
  
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命令.
 

行业门户(  )文章,希望大家可以留言建议

阅读(496) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~