-
2008-01-07
Linux下的sleep函数和fflush函数 - [C/C++]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://memorise.blogbus.com/logs/13442973.html
函数名: sleep
功 能: 执行挂起一段时间
用 法: unsigned int sleep(unsigned int seconds);
程序例:
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int i;
for (i=1; i<5; i++)
{
printf("Sleeping for %d seconds\n", i);
sleep(i);
}
return 0;
}另:
VC++中的Sleep函数原型为:
void Sleep(
DWORD dwMilliseconds
);
linux下的sleep函数原型为:
unsigned int sleep(unsigned int seconds);
MFC中的是微秒,linux下的是秒。linux下用微秒的线程休眠函数是:
void usleep(unsigned long usec);
int usleep(unsigned long usec); /* SUSv2 */
或者用select函数+timeval结构也可以(最多精确到微秒),
或者用pselect函数+timespec(可以精确到纳秒,足够精确了!)NAME
fflush - flush a stream
SYNOPSIS
#include <stdio.h>
int fflush(FILE *stream);
DESCRIPTION
The function fflush() forces a write of all user-space buffered data
for the given output or update stream via the stream’s underlying write
function. The open status of the stream is unaffected.
If the stream argument is NULL, fflush() flushes all open output
streams.
For a non-locking counterpart, see unlocked_stdio(3).
RETURN VALUE
Upon successful completion 0 is returned. Otherwise, EOF is returned
and the global variable errno is set to indicate the error.
ERRORS
EBADF Stream is not an open stream, or is not open for writing.
The function fflush() may also fail and set errno for any of the errors
specified for the routine write(2).
NOTES
Note that fflush() only flushes the user space buffers provided by the
C library. To ensure that the data is physically stored on disk the
kernel buffers must be flushed too, e.g. with sync(2) or fsync(2).用途:清空缓冲区,可以避免一些错误
当输出语句太多 用:fflush(stdout)
以上两个函数的例子程序:
#include <stdio.h>
#include <unistd.h>
int main()
{
int i,j;
for(i=0;i<=100;i++)
{
j = 1000;
printf("%d\n",i);
fflush(stdout);
sleep(1);
}
return 0;
}以上程序实现了动态显示1到100的数值。
收藏到:Del.icio.us





