首页 > 系统服务 > 详细

Linux popen()执行shell命令

时间:2021-07-10 16:22:37      阅读:15      评论:0      收藏:0      [点我收藏+]

函数原型

#include <stdio.h>

FILE * popen(const char *command , const char *type );
int pclose(FILE *stream);

popen 通过type是r还是w确定command的输入/输出方向,r和w是相对command的管道而言的。

r表示command从管道中读入,w表示 command通过管道输出到它的stdout

返回值: popen返回FIFO管道的文件流指针

关闭指针: pclose则用于使用结束后关闭这个指针

示例1

  FILE *stream;
  FILE *wstream;
  char buf[1024] = {0};
  stream = popen( "ls -l", "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream
  wstream = fopen( "test_popen.txt", "w+"); //新建一个可写的文件
  fread( buf, sizeof(char), sizeof(buf),  stream);  //将刚刚FILE* stream的数据流读取到buf中
  fwrite( buf, 1, sizeof(buf), wstream );//将buf中的数据写到FILE    *wstream对应的流中,也是写到文件中
  pclose( stream ); 
  fclose( wstream );

示例2

#include <cstdio>
                                                                                                                               
std::string create_container()
{
    std::string ret;
    FILE *fd = popen("./create_room.sh","r");
    if(fd != NULL)
    {   
        char buff[1024] = {0};
        fread(buff,2,sizeof(buff),fd);
        unsigned short port = atoi(buff);
        std::cout<<port<<std::endl;
        ret.append(buff);
        pclose(fd);
    }   
    return ret;
}
int main()
{
    create_container();
    return 0;
}

Linux popen()执行shell命令

原文:https://www.cnblogs.com/lodger47/p/14993350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!