在Linux中使用popen的例子.

来源:互联网 发布:知乎 阿子 编辑:程序博客网 时间:2024/05/05 02:50

    在Linux下进行编写程序的时候,如果需要执行一段脚本,并且需要获取脚本执行的结果,按么最好使用popen。下面就举一个例子:

c代码文件为: 3.C,内容如下:

  1.   #include   <sys/types.h>
  2.   #include <string.h>
  3.   #include   <unistd.h> 
  4.   #include   <stdlib.h>
  5.   #include   <stdio.h> 
  6.   #include <iostream.h>
  7.   typedef struct tag_Result
  8.   {
  9.     char filename[100];  
  10.     int filesize;      
  11.     tag_Result()
  12.     {
  13.         filename[0] = '0';
  14.         filesize    = 0;
  15.     }
  16.   }RESULT,*LPRESULT;
  17.   int   WriteFile(const   char   *filename,const   char   *pFile,const   int   nLen)   
  18.   {   
  19.                   FILE   *stream=NULL;   
  20.                   stream=fopen(filename,"w+");   
  21.                   if(stream==NULL)   
  22.                   {   
  23.                                   perror("Open   file   error");   
  24.                                   return   -1;   
  25.                   }   
  26.                   if(fwrite((void   *)pFile,1,nLen,stream)!=nLen)   
  27.                   {   
  28.                                   perror("Write   file   error");   
  29.                                   fclose(stream);   
  30.                                   return   -1;   
  31.                   }   
  32.                   fclose(stream);   
  33.                   return   0;   
  34.   }   
  35.   int   main()   
  36.   {   
  37.           RESULT res;
  38.           FILE   *pStream = NULL;   
  39.           char   buf[4096]={""};   
  40.       char dddd[10]={""};
  41.           char cccc[100]={""};
  42.           pStream=popen("a","r");   
  43.           if(pStream)
  44.       {   
  45.              fscanf(pStream,"%[^';'];%[^';'];%s",res.filename,cccc,dddd);
  46.          cout<<"filename:"<<res.filename<<endl;
  47.              cout<<"cccc:"<<cccc<<endl;
  48.              res.filesize = atoi(dddd);
  49.              cout<<"filesize:"<<res.filesize<<endl;
  50.              sprintf(buf,"%s,%d",res.filename,res.filesize);
  51.              WriteFile("result.txt",buf,strlen(buf));   
  52.              pclose( pStream);   
  53.           }
  54.       else
  55.           {
  56.              cout<<"popen Error!"<<endl;    
  57.       }
  58.           return 1;    
  59.   }   

要执行的脚本名称为a,脚本内容为:

  1. #!/bin/sh
  2. #filename: a
  3. fileinfo=11
  4. rm fileinfo #>/dev/null 2>
  5. echo -n $fileinfo";" >> fileinfo
  6. echo -n $fileinfo";" >> fileinfo
  7. ls -l $fileinfo | awk '{print $5 }' >> fileinfo
  8. cat fileinfo

通过:g++ -o 11 3.C  编译c代码生成可执行文件为:11,直接执行11,就可以查看到结果.

 

 

1.问题1: 如果脚本a在第3行的时候,直接就通过exit 1返回了,那么通过popen打开执行这个脚本会出现什么结果呢?

   如果脚本直接返回,相当于脚本没有向popen打开的文件中写入任何数据,也就是说popen相当于打开了一个空文件.

2.问题2: popen打开的文件中获取的是什么数据?

    获取的就是脚本输出到标准输出的数据。

 

 

 

 

 


原创粉丝点击