首页 > 解决方案 > 如何将 STDIN 传递给程序并将其输出存储到变量中?C

问题描述

我需要使用 bash 执行文件并将其输出存储到变量中,还需要将字符串s传递给它的标准输入。在 bash 中是这样的:

    usr:~$ s | program args

我知道如何调用程序并给他 args:

    execvp(program,args);

所以我的问题是给他的标准输入并将输出存储到变量(字符串)!

PS:不能使用system和popen。

标签: cbashexecstdinsystem-calls

解决方案


一些示例代码供您体验。这个执行ls | cat

 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main(int argc, char** argv) {
     int fd[2];
     int pid;
     char* cmd1[2] = {"ls", NULL};
     char* cmd2[2] = {"cat", NULL};
     int status;

     pid = fork();
     if (pid == 0) {
         pipe(fd);
         pid = fork();
         if (pid == 0) {
             printf("cmd1\n");
             dup2(fd[1], 1);
             close(fd[0]);
             close(fd[1]);
             execvp(cmd1[0], cmd1);
             printf("Error in execvp\n");
         }
         else {
             dup2(fd[0], 0);
             close(fd[0]);
             close(fd[1]);
             printf("cmd2\n");
             execvp(cmd2[0], cmd2);
             printf("Error in execvp\n");
         }
     }
     else {
         close(fd[0]);
         close(fd[1]);
         wait(&status);
         printf("%d\n", status);
         wait(&status);
         printf("%d\n", status);
     }
 }



推荐阅读