执行一个命令,将其输出截获的代码-使用无名管道

使用popen库函数的版本:


    #include  < unistd.h >
    #include 
< stdio.h >
    #include 
< stdlib.h >
    #include 
< fcntl.h >
    #include 
< limits.h >

    
#define  BUFSZ PIPE_BUF

    
void  err_quit( char   * msg);

    
int  main( int  argc,  char   * argv[])
    {
        FILE 
* fp;   //  FILE stream for popen
         char   * cmdstring  =   " ps -aux|grep root " ;
        
char  buf[BUFSZ];

        
//  create the pipe
         if  ((fp  =  popen(cmdstring,  " r " ))  ==  NULL)
            err_quit(
" popen " );

        
//  read the cmdstring's output
         while  ((fgets(buf, BUFSZ, fp))  !=  NULL)
            printf(
" %s " , buf);

        
//  close and frap the exit status
        pclose(fp);
        exit(EXIT_SUCCESS);
    }

    
void  err_quit( char   * msg)
    {
        perror(msg);
        exit(EXIT_FAILURE);
    }

 

不使用库函数,自己实现的版本(先fork,然后修改子进程的STDOUT文件描述符为管道,然后再exec),这个思路来自Linux Shells by Examples一书,因为BASH执行命令就是酱紫的:

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

    
#define  BUFSZ PIPE_BUF

    
void  err_quit( char   * msg);

    
int  main( int  argc,  char   * argv[])
    {
        
int  fd[ 2 ];  //  File descriptor array for the pipe
         char  buf[BUFSZ];
        
char   * cmdstring[]  =  { " /bin/ps " " -aux " , NULL};
        
int  pid, len;

        
//  create the pipe
         if  ((pipe(fd))  <   0 )
            err_quit(
" pipe " );

        
//  fork and close the appropriate descriptors
         if  ((pid  =  fork())  <   0 )
            err_quit(
" fork " );
        
if  (pid  ==   0 ) {
            
//  child will invoke the cmdstring, so close stdout, dup pipewriter
            close(STDOUT_FILENO);
            dup(fd[
1 ]);
            close(fd[
0 ]);
            
//  invoke the cmdstring
             if  (execve(cmdstring[ 0 ], cmdstring, NULL)  ==   - 1 )
                err_quit(
" execve " );
        } 
else  {
            
//  parent process
            close(fd[ 1 ]);

            
while  ((len  =  read(fd[ 0 ], buf, BUFSZ))  >   0 )
                printf(
" %s " , buf);
            close(fd[
0 ]);

            waitpid(pid, NULL, 
0 );

            exit(EXIT_SUCCESS);
        }
    }

    
void  err_quit( char   * msg)
    {
        perror(msg);
        exit(EXIT_FAILURE);
    }

 

你可能感兴趣的:(命令)