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 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703142 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708052 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习2 小时前
【算法——c/c++]
c语言·c++·算法
m0_748233174 小时前
30秒掌握C++核心精髓
开发语言·c++
风清扬_jd4 小时前
libtorrent-rasterbar-2.0.11编译说明
c++·windows·p2p
u0109272714 小时前
C++中的RAII技术深入
开发语言·c++·算法
彷徨而立5 小时前
【C/C++】strerror、GetLastError 和 errno 的含义和区别?
c语言·c++
誰能久伴不乏5 小时前
【Qt实战】工业级多线程串口通信:从底层协议设计到完美收发闭环
linux·c++·qt
2401_832131955 小时前
模板错误消息优化
开发语言·c++·算法