我在這裏得到了一個阻止fgets的函數,但是當我在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);
}
上面的函數有什麼問題嗎?
是的錯,你不關閉寫過程的結束,你也讀取。 –
[popen(3) - Linux man page](http://linux.die.net/man/3/popen「)有用的信息。 – chux
@Grijesh Chauhan - 你可以請你重述一下你的信息我不明白你發佈了什麼 – kuchi