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);
 }
			  
相关推荐
Lzg_na3 小时前
僵尸进程、孤儿进程、守护进程:含义、区别与生命周期详解
c++
zhanghaha13143 小时前
C++ 的类是什么(新手保姆讲解,配合 Qt 对照理解)
c++
aqiu1111113 小时前
【C++算法打怪专栏】LeetCode 402. 移掉 K 位数字(单调栈 + 贪心)
c++·算法·leetcode
(Charon)3 小时前
【C++面试】线程并发与异步:区别、实现原理及使用场景
开发语言·c++
JMchen4 小时前
实战项目一——实现一个高性能图片滤镜App
android·c++·性能优化
码匠许师傅4 小时前
【C++三方组件】libpqxx:PostgreSQL 的 C++ 客户端
开发语言·c++·postgresql
H.莓飛4 小时前
【C++】内存管理
linux·开发语言·jvm·c++·visual studio
longlongzihan5 小时前
从LeetCode 19. 删除链表的倒数第 N 个结点深入理解“哨兵节点”
c++·算法·leetcode·链表
爱吃提升5 小时前
Dev-C++ 5.11 完整版快捷键大全(信奥/初学适用)
c语言·c++
SWAGGY..6 小时前
【C++进阶】:(10)哈希表的原理与实现——从哈希函数到哈希桶
c++·哈希算法·散列表