Linux 下 怎么样向shell命令中输入参数并获取输出内容

C++语言 码拜 7年前 (2017-05-02) 3803次浏览
例如 mysql 命令,当你使用mysql登陆时,会要你输入用户名和密码,然后就可以执行sql语句,界面会返回sql的结果。
现在就想 在程序中集成这些操作,将这些输入输出放到程序中,问一下有什么好办法吗?
解决方案

20

C语言可通过popen执行shell命令,fgets获取输出,pclose关闭。
很多命令都是可以一步到位的,不用一步一步的交互(例如提示输入密码,然后用户再输入密码)。
例如mysql,执行查询命令 mysql -hlocalhost -uroot -pmypwd -e “select * from mydb.mytbl”
在C程序中调用popen(“mysql -hlocalhost -uroot -pmypwd -e “select * from mydb.mytbl” “, “r”),然后用fgets获取输出结果

10

popen实际上建立了管道,一般执行shell命令都一步到位即可,没必要非要输入,若果你非要输入的话,也可以用fputs输入,然后再fgets获取结果。

10

仅供参考:

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
pid_t rw_popen(char* cmd, FILE **rfile, FILE **wfile) {
    int pipefd[2],pipefd2[2]; //管道描述符
    pid_t pid; //进程描述符
    if (pipe(pipefd) < 0) //建立管道
    {
        printf("rw_popen() pipe create error/n");
        return 0;
    }
    if (pipe(pipefd2) < 0) //建立管道
    {
        printf("rw_popen() pipe create error/n");
        return 0;
    }
    pid = fork(); //建立子进程
    if (pid < 0)
    return 0;
    if (0 == pid) //子进程中
    {
        close(pipefd[0]);
        dup2(pipefd[1], 1);
        close(pipefd[1]);
        dup2(pipefd2[0], 0);
        close(pipefd2[0]);
        close(pipefd[1]);
        char *argv[] = { "/bin/sh", "-c", cmd, NULL };
        if (execvp("/bin/sh", argv) < 0) //用exec族函数执行命令
        exit(1);
    }
    close(pipefd[1]);
    *rfile = fdopen(pipefd[0], "r");
    close(pipefd2[0]);
    *wfile = fdopen(pipefd2[1], "w");
    return pid;
}
void rw_pclose(pid_t pid, FILE *rfile, FILE *wfile) {
    int status;
    waitpid(pid, &status, 0);
    fclose(rfile);
    fclose(wfile);
}
int main() {
    char buf1[1024];
    FILE *file1, *file2;
    pid_t pid;
    pid = rw_popen("sh", &file1, &file2);
    if (pid) {
        fputs("pwd;exit;\n",file2);
        fflush(file2);
        if (fgets(buf1, 1400, file1)) {
            puts(buf1);
        }
        rw_pclose(pid, file1, file2);
    }
    return 1;
}

10

mysql 或其他软件本身有相似直接在控制台运行的吧
如   mysql   -Dxxx   -e “xxx.sql”    >  重定向文件  | grep  “你想要的”

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Linux 下 怎么样向shell命令中输入参数并获取输出内容
喜欢 (0)
[1034331897@qq.com]
分享 (0)