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);
 }
			  
相关推荐
喜欢吃燃面2 小时前
数据结构算法题:list
开发语言·c++·学习·算法·1024程序员节
胡萝卜3.02 小时前
C++ list核心接口与实战技巧
数据结构·c++·list·list使用
。TAT。2 小时前
C++ - 多态
开发语言·c++·学习·1024程序员节
mit6.8242 小时前
[cpprestsdk] JSON类--数据处理 (`json::value`, `json::object`, `json::array`)
c++·1024程序员节
武当豆豆2 小时前
C++编程学习(第42天)
开发语言·c++·学习
咬_咬2 小时前
C++仿muduo库高并发服务器项目:Channel模块
linux·c++·channel·1024程序员节·muduo·高并发服务器
jdlxx_dongfangxing3 小时前
C++ STL 容器与算法详解
开发语言·c++·1024程序员节
m0_748233644 小时前
C++ 模板初阶:从函数重载到泛型编程的优雅过渡
java·c++·算法·1024程序员节
Hyt的笔记本4 小时前
【C++】异步操作
c++·1024程序员节
yolo_guo5 小时前
C++ ABI:编译报错之:gcc 4.8.1 切 gcc 6.1.0
c++