This program is called program.c. When I run ./program echo test, I would expect the program to print test, even if the command is run in a subshell. Why is the output an empty line? Does it have to do with filepath? When I try ./program /bin/echo test I still get an empty line output.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int function(char **argv) {
execl("/bin/bash", "sh", "-c", *argv, argv, (char*)NULL);
}
int main(int argc, char **argv) {
int return2;
function(argv + 1);
}
There are two problems with your program.
The first problem is that the argument
argvtoexecl()does not do what you think it does. The pointerargvis a pointer to achar *(i.e. achar **), and it is only permitted to pass achar *as an argument toexecl(). That is, variable argument lists in C do not work how you are expecting them to.In order to accomplish what you want, consider not using
execl()and useexecv()instead, passing an array ofchar *s which you have constructed yourself. You could do this in the following way, for example:However, you still have a problem:
./program echo testwill still print a blank line because if you executesh -c echo testin a terminal you just get a blank line! In order to fix this, you need to do./program 'echo test'(corresponding tosh -c 'echo test'at the terminal), which should then work.