alarm流量控制1

cpp 复制代码
#include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <errno.h>
 #include <signal.h>
 #include <unistd.h>
 
 #define CPS 10
 #define BUFSIZE CPS
 #define BURST 100
 
 static volatile int token = 0;
 
 static void alarm_handler(int s)
 {
     alarm(1);
     token++;
     if(token > BURST)
         token = BURST;
 }
 
 
 int main(int argc, char *argv[])
 {
     int sfd, dfd = 1;
     char buf[BUFSIZE];
     int len, ret, pos;
 
     if(argc < 2)
	 {
         fprintf(stderr, "Usage....\n");
         exit(1);
     }
     signal(SIGALRM, alarm_handler);
     alarm(1);
 
     do
     {
         sfd = open(argv[1], O_RDONLY);
         if(sfd < 0)
         {
             if(errno != EINTR)
             {
                 perror("open()");
			 }
         }
 
     }while(sfd < 0);
 
     while(1)
     {
         while(token <= 0)
         {
             pause();
         }
         token--;
         while((len = read(sfd, buf, BUFSIZE)) < 0)
         {
             if(errno == EINTR)
			 continue;
             perror("read()");
             break;
         }
         if (len == 0)
         {
             break;
         }
         pos = 0;
         while(len > 0)
         {
            ret =  write(dfd, buf + pos, len);
            if(ret < 0)
            {
              if(errno == EINTR)
				continue;
              perror("read()");
              break;
            }
            len -= ret;
            pos += ret;
         }
 
     }
     exit(0);
 }
			  
相关推荐
码匠许师傅10 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
xxwxx__11 小时前
C++ list 深度解析:从使用原理到模拟实现
开发语言·c++·list
Chester_199912 小时前
CSP202303C.LDAP
开发语言·c++·蓝桥杯·stl
j7~13 小时前
【C++】《unordered系列关联式容器以及哈希底层、哈希冲突、闭散列与开散列完整解析》
c++·哈希算法·开散列·闭散列·unordered_map·unordered_set·哈希底层结构
2402_8828938613 小时前
封装红黑树实现map和set —— 从源码到模拟实现
c++·set·map
神仙别闹14 小时前
基于C++ MFC 实现的智慧公交系统
开发语言·c++·mfc
dear_bi_MyOnly15 小时前
函数模块化:企业级项目高效之道
c++·后端·学习
码匠许师傅15 小时前
【设计模式精讲】13.装饰器模式(Decorator)
c++·设计模式·uml·装饰器模式
OPEN-F15 小时前
C++综合实战:面向对象图书管理系统
开发语言·c++
NeoGressAI外贸数字化16 小时前
外贸独立站零询盘排查:从 Google Search Console 到 PageSpeed 的技术实操
开发语言·c++