You've not specified the return type of the function, so the compiler assumes it returns an int
, but you're trying to return a char *
. Note that pre-standard C and C89 allowed this 'implicit return type'. C99 and beyond require the return type. Compilers still allow the code through because of the pre-standard legacy code.
You're trying to return the local variable output
, but that variable vanishes when the function returns. (You also return a pointer to an uninitialized variable if the popen()
fails. And you ignore the gcommand
parameter that's passed to the function.)
You should probably pass the buffer and its size to the function:
int shell_command(const char *gcommand, char *buffer, size_t buflen)
{
FILE *pipe = popen(gcommand, "r");
if (pipe)
{
char *result = fgets(buffer, buflen, pipe);
pclose(pipe);
if (result != 0)
return 0;
}
return -1;
}
This returns 0 on success and -1 on failure, and (now) checks the return value from fgets()
which could fail, but ensures that the pipe is closed regardless.