Fgets returning error for FILE returned by popen

I am trying to execute a command line from my C code, but when I go 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 team:

 java -jar <parameters> 

Why do I have a NULL result from fgets, even though when I try to execute the same command in the terminal, it works as expected.

+4
source share
1 answer

fgets () reads no more than one character of size from the stream and saves them to the buffer pointed to by s. Reading stops after EOF or a new line. If a new line is read, it is saved in the buffer. A '\ 0' is stored after the last character in the buffer.

In short, popen() executes fork() , and you try to read from the pipe before the program called by cmd produces output, so there is no data on the pipe and the first read on the pipe returns EOF , so fgets() returns without receiving data . You need to either sleep, or do a survey, or read the lock.

+4
source

All Articles