PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

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

 September 15, 2022     bash, c, exec, stdin, system-calls     No comments   

Issue

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. Something like this in bash:

    usr:~$ s | program args

I know how to call the program and give him args:

    execvp(program,args);

So my problem is giving to that his stdin and store output to a variable(string)!

P.S.:can't use system and popen.


Solution

Some example code for you to experiement. This excute 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);
     }
 }




Answered By - Bruce Shen
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing