天下

记录修行的印记

linux pexec函数

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

int pexec(const char* command,int* result)
{
    
int pid;
    
int fds[2= {-1,-1};
    
int status = -1;

    
if(pipe(fds) < 0
    {
        
return -1;
    }

    
if( (pid=vfork()) < 0)
    {
        close(fds[
0]);
        close(fds[
1]);
        
return -1;
    }

    
if (pid == 0 )
    {
        dup2(fds[
1],1);
        close(fds[
0]);
        close(fds[
1]);
        execl(
"/bin/sh""sh""-c", command,NULL);
        _exit(
-1);
    }
    
else
    {
        waitpid(pid,
&status,0);
        close(fds[
1]);
        
if (WIFEXITED(status)==0
        {
            close(fds[
0]);
            
return -1;
        }
        status  
= WEXITSTATUS(status);
        
if (result!=NULL) 
        {
            
*result = status;
        }
        
//printf("pid(%d) exited,status:%d \r\n",pid,status);
        return fds[0];
    } 
}

int main(int argc,char* argv[]) 
{
    
if (argc<2)
    {
        printf(
"Usage:%s <cmd> \r\n",argv[0]);
        
return -1;
    }
    
int status = -1;
    
int fd = pexec(argv[1],&status);
    
if (fd==-1)
    {
        printf(
"pexec(%s) error \r\n",argv[1]);
        
return -1;
    }
    
char buf[4097];
    
int readed = 0;
    
while( (readed = read(fd,buf,4096))>0)
    {
        buf[readed] 
= 0;
        printf(
"readed:%d\r\n%s",readed,buf);
    }
    close(fd);
    
return 0;
}

posted on 2012-08-10 09:23 天下 阅读(521) 评论(0)  编辑 收藏 引用 所属分类: Linux编程


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2012年8月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(4)

随笔分类(378)

随笔档案(329)

链接

最新随笔

搜索

最新评论