簡體   English   中英

如何將 STDIN 傳遞給程序並將其 output 存儲到變量中? C

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

我需要使用 bash 執行文件並將其 output 存儲到變量中,還需要將字符串s傳遞給其標准輸入。 bash 中的類似內容:

    usr:~$ s | program args

我知道如何調用程序並給他 args:

    execvp(program,args);

所以我的問題是給他的標准輸入並將 output 存儲到變量(字符串)!

PS:不能使用system和popen。

一些示例代碼供您體驗。 這個執行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