问一下怎么样将标准输出重定向到某个控件上

C语言 码拜 7年前 (2017-04-18) 942次浏览
linux上,调用system执行sh解压文件,能否将其输出到标准输出上的信息实时地转输到窗口上的控件上,例如文本控件?
解决方案

20

仅供参考:

#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

linux不是有fmemopen么

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明问一下怎么样将标准输出重定向到某个控件上
喜欢 (0)
[1034331897@qq.com]
分享 (0)