Linux下使用popen()执行shell命令


简单说一下popen()函数

函数定义
#include <stdio.h>

FILE * popen(const char *command , const char *type );
int pclose(FILE *stream);函数说明
  popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。这个管道必须由pclose()函数关闭,而不是fclose()函数。pclose()函数关闭标准I/O流,等待命令执行结束,然后返回shell的终止状态。如果shell不能被执行,则pclose()返回的终止状态与shell已执行exit一样。

  type参数只能是读或者写中的一种,得到的返回值(标准I/O流)也具有和type相应的只读或只写类型。如果type是"r"则文件指针连接到command的标准输出;如果type是"w"则文件指针连接到command的标准输入。

  command参数是一个指向以NULL结束的shell命令字符串的指针。这行命令将被传到bin/sh并使用-c标志,shell将执行这个命令。

  popen()的返回值是个标准I/O流,必须由pclose来终止。前面提到这个流是单向的(只能用于读或写)。向这个流写内容相当于写入该命令的标准输入,命令的标准输出和调用popen()的进程相同;与之相反的,从流中读数据相当于读取命令的标准输出,命令的标准输入和调用popen()的进程相同。

返回值
  如果调用fork()或pipe()失败,或者不能分配内存将返回NULL,否则返回标准I/O流。popen()没有为内存分配失败设置errno值。如果调用fork()或pipe()时出现错误,errno被设为相应的错误类型。如果type参数不合法,errno将返回EINVAL。

附上一个例子:

//execute shell command
//执行一个shell命令,输出结果逐行存储在resvec中,并返回行数
int32_t myexec(const char *cmd, vector<string> &resvec) {
    resvec.clear();
    FILE *pp = popen(cmd, "r"); //建立管道
    if (!pp) {
        return -1;
    }
    char tmp[1024]; //设置一个合适的长度,以存储每一行输出
    while (fgets(tmp, sizeof(tmp), pp) != NULL) {
        if (tmp[strlen(tmp) - 1] == '\n') {
            tmp[strlen(tmp) - 1] = '\0'; //去除换行符
        }
        resvec.push_back(tmp);
    }
    pclose(pp); //关闭管道
    return resvec.size();
}
 
上面的那个vector<string>感觉不是很常用,所以改成一下sting版本了:

int myexec(const char *cmd, string &resvec)
 {
    resvec.clear();
    FILE *pp = popen(cmd, "r"); //建立管道
    if (!pp)
    {
        return -1;
    }
    char tmp[1024]; //设置一个合适的长度,以存储每一行输出
    while (fgets(tmp, sizeof(tmp), pp) != NULL)
    {
        if (tmp[strlen(tmp) - 1] == '\n')
        {
            tmp[strlen(tmp) - 1] = '\0'; //去除换行符
        }
        resvec.append(tmp);
    }
    pclose(pp); //关闭管道
    return resvec.size();
}

使用时候:

string str_kernel;
myexec("uname -sr",str_kernel);
cout<<str_kernel<<endl;

Shell编程浅析  

Linux Shell参数替换

Shell for参数

Linux/Unix Shell 参数传递到SQL脚本

Shell脚本中参数传递方法介绍

Shell脚本传递命令行参数

Linux Shell 通配符、转义字符、元字符、特殊字符

本文永久更新链接地址:

相关内容