我在这里有一个功能可以阻止 fgets 但是当我在 fgets 之前打印一些东西时它不会阻止。
int exec_command(char *command, char *output_buf, int buf_size)
{
FILE* pipe = NULL;
char buffer[BUFFER_SIZE];
char tmp[SMALL_BUFFER_SIZE];
unsigned total_read = 0;
pipe = popen( command, "r");
if( !pipe )
{
//Error
return -1;
}
memset(buffer, 0, sizeof(buffer));
while( !feof(pipe) )
{
//printf("reading"); //If I uncomment this fgets doesnt block
if( fgets(tmp, sizeof(tmp), pipe) != NULL )
{
// check that it'll fit:
size_t len = strlen(tmp);
if (total_read + len >= sizeof(buffer))
break;
// and add it to the big buffer if it fits
strcat(buffer, tmp);
total_read += len;
}
}
//Is there anything to copy
if ( total_read )
strncpy (output_buf, buffer, buf_size);
return pclose(pipe);
}
我上面的功能有什么问题吗?