简体   繁体   English

如何将 STDIN 传递给程序并将其 output 存储到变量中? C

[英]How to pass STDIN to a program and store its output to a variable? C

I need to execute a file from the bash using and store its output to a variable, there's also the needs to pass to its stdin a string s .我需要使用 bash 执行文件并将其 output 存储到变量中,还需要将字符串s传递给其标准输入。 Something like this in bash: bash 中的类似内容:

    usr:~$ s | program args

I know how to call the program and give him args:我知道如何调用程序并给他 args:

    execvp(program,args);

So my problem is giving to that his stdin and store output to a variable(string)!所以我的问题是给他的标准输入并将 output 存储到变量(字符串)!

PS:can't use system and popen. PS:不能使用system和popen。

Some example code for you to experiement.一些示例代码供您体验。 This excute ls | cat这个执行ls | cat ls | cat . 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);
     }
 }


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM