I'm working in C and I have a problem when calling popen with the following arguments:
void exampleFunction(void)
{
.
.
.
FILE* in = popen("alias -p", "r");
.
.
.
}
When I call popen this way I get the following message:
alias: -p not found
I don't know what is actually wrong because when I call popen with the following arguments:
FILE* in = popen("ls -i", "r");
There is no problem and I'm using the same syntax.
Maybe someone realizes what's actually wrong.
The alias command is built into the shell.
popen, like system(), invokes /bin/sh to execute the specified command. Your interactive shell is probably bash, which supports a -p option to alias. /bin/sh, depending on your system configuration, probably does not.
In any case, even if this worked it wouldn't give you any useful information. The popen() call would invoke a new shell, and (again, depending on your configuration), it likely wouldn't have your aliases set up, since it's not an interactive shell.
The ls -i command works because ls is an external command, so it works the same way regardless of whether it's invoked from bash or /bin/sh, or from an interactive or non-interactive shell. (Sometimes ls can be defined as an alias or shell function, but such definitions typically don't interfere with the use of the -i option.)
alias is no executable program but a shell built-in (think of it as a "function in bash scripting language") so you can't open a process by this name. You could try to fool bash and pipe it in. Something like this untested snippet:
FILE* p = popen("/bin/bash", "r"); // Note: on non-Linux-systems you might need another path or rely on $PATH
fprintf(p, "alias -p\n");
Mind that you can't call aliases directly either.
The difference to ls is that ls exists both, as built-in an as program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With