设置缓冲区类型的函数主要有:
#include <stdio.h>
void setbuf(FILE *stream, char *buf);
void setbuffer(FILE *stream, char *buf, size_t size);
void setlinebuf(FILE *stream);
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
缓冲区的三种类型:
_IONBF unbuffered
_IOLBF line buffered
_IOFBF fully buffered
例子:设置缓冲区为不缓冲,父子进程竞争标准输出资源
#include <unistd.h>
#include <stdio.h>
static void charatatime(char* str)
{
char* ptr;
int c;
setbuf(stdout, NULL);
for(ptr = str; (c = *ptr++) != 0; )
{
putc(c, stdout);
}
}
int main()
{
pid_t pid;
if((pid = fork()) < 0)
{
printf("fork error");
}
else if(pid == 0)
{
charatatime("output from child\n");
}
else
{
charatatime("output from parent\n");
}
exit(0);
}
三次不同的输出如下
chanlp@chanlp-Presario-V3700-Notebook-PC:~$ ./a
ooutput froumt pcuhti lfdr
om parent
chanlp@chanlp-Presario-V3700-Notebook-PC:~$ ./a
output from parent
chanlp@chanlp-Presario-V3700-Notebook-PC:~$ output from child
./a
output from parent
output from child
chanlp@chanlp-Presario-V3700-Notebook-PC:~$ ./a
ooutput from chuitlpdu
t from parent