linux printf()缓冲区的问题

linux下的printf();

现将要输出的内容输出到,缓冲区中然后,在以下条件下,再由缓冲区输出到屏幕,
   1.使用fflush(stdout)强制刷新。
   2.缓冲区已满。
   3.scanf()要在缓冲区里取数据时会先将缓冲区刷新。
   4.\n,\r进入缓冲区时。
   5.线程结束的时候,如果该线程里也有printf(....);
   6.程序结束时。(进程结束时)
==================以上由网友提供==============================================================
 
在Linux下运行以下程序。
 
#include <stdio.h>
void main()
{
 printf("1");
 printf("2");
 printf("3");
 printf("4");
 sleep(3);
 printf("ok");
}

结果不是我们想像的,输出1234停止三秒然后输出ok。
运行情况是这样的,
将1234输送到缓冲区(由于没有达到从缓冲区输送到屏幕上的任意一项,因此不进行输出,等待,程序停止三秒,将ok存到缓冲区,程序结束(主进程结束),此时将缓冲区的内容输送至屏幕)
导致我们看到的是,三秒停滞,然后出现1234ok。
 
我们可以改变程序使他,达到刷新缓冲区的效果
 
以及fpirntf();
有和printf();类似的机制。因此写文件是要注意。
 
还有个小问题,printf("....",表达式1,表达式2,表达式3,...);
 
中的表达时自右向左执行的。
 
#include <stdio.h>
int main()
{
 int a=0,b=0,c=0,d=0;
 printf("%d %d %d%d\n",a+=b,b+=c,c+=d,d+=1);
}
 
以下是求助,也是上述fprintf();结论给出的原因。求大侠解释。
=============================================================================================
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void* showy(void* argv);
void * showx(void * argv )
{
 int x=3;
 int y=3,z=3;
 pthread_t showythread;
 int status_2;
 printf("x is:%d  y:%dz:%d\n",x,y,z);
 //printf("main a:%d x:%d\n",*((int *)argv),x);
 pthread_create(&showythread,NULL,showy,(void*)(&x));
 pthread_join(showythread,(void*)(&status_2));
 //sleep(3);
 //printf("%p %p%p\n",&x,&y,&z);
 printf("\nx is:%d  y:%dz:%d\n",x,y,z);
 printf("y deat case :%d\n",status_2);
 printf("showx thread start!\n");
 x=3;
 while(x>0)
 
  printf("x:%d",x);
  x--;
  sleep(1);
 }
 printf("showx thread ending!\n");
 pthread_exit((void*)3);
}
void* showy(void* argv)
{
 int y=3;
 while(y>0)
 {
  printf("y:%d\n",y);
  y--;
  sleep(1);
 }
 printf("y is ending!\n");
 pthread_exit((void*)3);
}
int  main()
{
 FILE *fp;
 pthread_t showxthread;
 int a=2,b=2,c=2,ta,tb,tc;
 int status;
 printf("main a:%d b:%d c:%d\n",a,b,c);
 if(pthread_create(&showxthread,NULL,showx,(void*)(&a))==0)
 
  printf("threadshowxruning!\n");
 }
 pthread_join(showxthread,(void*)(&status));
 printf("-------------main a:%d b:%dc:%d\n",a,b,c); //与下面的对比,在于文件中的数据对比,该句的输出内容让人误解b竟然成了零。(然而文件中却正常,去掉该语句文件输出 2依旧正常,就解释,printf,(在不同的机器配置貌似都不太一样))
// fflush(stdin);
 // printf("%p %p%p\n",&a,&b,&c);
 putchar('*');
 fp = fopen ("1.txt","wt");
 //fprintf(fp,"%d %d %d",a,b,c);
 fwrite(&a,4,1,fp);
 fwrite(&b,4,1,fp);
 fwrite(&c,4,1,fp);
 fclose(fp);
 
 fp = fopen ("1.txt","rt");
 fread(&ta,4,1,fp);
 fread(&tb,4,1,fp);
 fread(&tc,4,1,fp);
 fclose(fp);
 printf("%d %d %d\n",ta,tb,tc);
 //write(1, (void *)&a,sizeof(int)*3);
 printf("\nmain a:%d b:%d c:%d\n",a,b,c);(由于上述写操作,回复正确的输出);
 printf("main process is dead! cause:%d\n",status);
 return 0;
}
 

文件中的数据让人安心多了,在产生新线程前后,该线程中的数据,不会因为,他所等待的线程空间释放,而改变。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值