I'm trying to execute a command line from my C code, but when I get to the fgets() function, I got a NULL error.
void executeCommand(char* cmd, char* output) {
FILE *fcommand;
char command_result[1000];
fcommand = popen(cmd, "r");
if (fcommand == NULL) {
printf("Fail: %s\n", cmd);
} else {
if (fgets(command_result, (sizeof(command_result)-1), fcommand) == NULL)
printf("Error !");
strcpy(output, command_result);
}
pclose(fcommand);
}
And my command is:
java -jar <parameters>
Why do I have a NULL result from fgets, despite that when I try to execute the same command in a terminal, it works as expected.
In short, the
popen()
is doing afork()
and you're trying to read from the pipe before the program evoked bycmd
has produced output, therefor there is no data on the pipe and the first read on the pipe will returnEOF
, sofgets()
returns without getting data. You either need to sleep, do a poll or do a blocking read.