1
我正在玩管道,並從here採取以下代碼;一旦我明白了,我看到一個數據塊緩存的問題,我添加了一個電話到sleep()
,這是不存在的原始代碼:沖洗管道的緩衝區
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
FILE *ps_pipe;
FILE *grep_pipe;
int bytes_read;
int nbytes = 100;
char *my_string;
char buffer[100];
/* Open our two pipes */
ps_pipe = popen ("ls", "r");
grep_pipe = popen ("sort", "w");
/* Check that pipes are non-null, therefore open */
if ((!ps_pipe) || (!grep_pipe))
{
fprintf (stderr,
"One or both pipes failed.\n");
return EXIT_FAILURE;
}
bytes_read = 0;
while (fgets(buffer, sizeof(buffer), ps_pipe))
{
fprintf(grep_pipe, "%s", buffer);
bytes_read += strlen(buffer);
}
printf("Total bytes read = %d\n", bytes_read);
sleep(2);
/* Close ps_pipe, checking for errors */
if (pclose(ps_pipe) != 0)
{
fprintf(stderr, "Could not run 'ps', or other error.\n");
}
/* Close grep_pipe, cehcking for errors */
if (pclose(grep_pipe) != 0)
{
fprintf(stderr, "Could not run 'grep', or other error.\n");
} /* Exit! */
return 0;
}
EDIT [這是錯的,見下面的回答]:這樣,一旦程序從其主函數返回,我確信管道的緩衝區被刷新。
但是,我仍然不明白原因:爲什麼管道的內核緩衝區會刷新到標準輸出?前者與後者有什麼關係? [編輯:這也是錯誤的,但留給上下文]
謝謝你澄清它。 – HeyJude