I wrote a c program as below:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a;
scanf("%d",&a);
system("/bin/sh");
return 0;
}
compiled it and when i execute the a.out file it shows something like this:
user@system:~/dir$ ./a.out
123 <- this is the input that I gave
$ whoami
user
so here I get a proper sub shell called through c
now if I execute the a.out file using input through pipe it shows like this:
user@system:~/dir$ echo 123 | ./a.out
user@system:~/dir$
it simply executes the command, creates the shell, terminates the shell and exits.
I am sure that it executes the sub shell because on doing echo 123 | ltrace ./a.out
it shows like this:
system("/bin/sh" <no return ...>
--- SIGCHLD (Child exited) ---
<... system resumed> ) = 0
+++ exited (status 0) +++
which means there is a sub shell created
I cant understand what difference does the two methods make
sh
will read the stdin
till it is encountering the EOF.
In the first case you do not send EOF
(which can be done by pressing Ctrl-D
depending on your environment). In the second case the EOF
is happening after the piped input is exhausted (that is after the echo 123
is done).
To understand better you can simulate the sh
behavior with a simple program:
#include <stdio.h>
int main(void)
{
char input[100];
while(fgets(input, 100, stdin)) {
printf("Echoing back: %s\n", input);
}
return 0;
}
You can compile it and run with your system()
call instead of sh
and observe a similar behavior.