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);
 }
			  
相关推荐
zyx没烦恼37 分钟前
五种IO模型
开发语言·c++
EutoCool1 小时前
Qt窗口:菜单栏
开发语言·c++·嵌入式硬件·qt·前端框架
圆头猫爹3 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
十五年专注C++开发4 小时前
hiredis: 一个轻量级、高性能的 C 语言 Redis 客户端库
开发语言·数据库·c++·redis·缓存
hi0_64 小时前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
碧海蓝天20224 小时前
C++法则21:避免将#include放在命名空间内部。
开发语言·c++
CodeWithMe5 小时前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
Tanecious.6 小时前
C++--红黑树
开发语言·c++
tanyongxi669 小时前
C++ Map 和 Set 详解:从原理到实战应用
开发语言·c++
飒飒真编程9 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法