Home > Software design >  Starting a sh shell in c doesn't work if I pipe the input to the executable
Starting a sh shell in c doesn't work if I pipe the input to the executable

Time:06-20

I have this code right here:

#include <string.h>
#include <unistd.h>

int main(void)
{
    char buff[15];
    int pass = 0;
    int a[30];
    char *args[2];
    args[0] = "/bin/sh";
    args[1] = NULL;

    printf("\n Enter the password : \n");
    scanf("%s",buff);

    execve ("/bin/sh", args, NULL);
    

    return 0;
}

I compiled the code using gcc. When I run the executable normally with ./myexec the code runs normally. I get the prompt asking for the password and after I input anything the sh shell starts.

But when I do something like python -c 'print "someinput"' | ./myexec the shell doesn't start, or at least it doesn't on the same terminal from which I ran the executable, because I checked for some errno messages and nothing seemed to go wrong but neither ''' ps -a | grep sh ``` doesn't show any background shells open so I don't know what to make of it.

CodePudding user response:

When you run python -c 'print("someinput")' | ./myexec, you're telling your shell to take the output of the first command, in this case python ... and pipe it as the input of the second one (./myexec). When the input has been consumed, that's it, there's nothing more that your shell can pipe into the second program.

To make this work, add a cat invocation: (python -c 'print("someinput")'; cat) | ./myexec

cat, when given no file to read, will just echo data from its stdin, and so it provides you with a way to input data manually in the pipe after python completes.

  • Related