linux信号常用函数

1.kill

发送一个信号给一个进程

NAME
 kill - send signal to a process

SYNOPSIS
 #include <sys/types.h>
 #include <signal.h>

 int kill(pid_t pid, int sig);

DESCRIPTION
 The  kill()  system  call  can  be  used  to  send any signal to 
 any process group or process.

在这里插入图片描述

2.raise

自己给自己发一个信号

NAME
       raise - send a signal to the caller

SYNOPSIS
       #include <signal.h>

       int raise(int sig);

DESCRIPTION
  The  raise()  function sends a signal to the calling process 
  or thread.  In a single-threaded program it is 
  equivalent to kill(getpid(), sig);

In a multithreaded program it is equivalent to
 pthread_kill(pthread_self(), sig);

3.alarm

每个进程只能有一个闹钟时间,后面注册的闹钟会变成新的时间,并且把旧的时间作为返回值返回

NAME
 alarm - set an alarm clock for delivery of a signal

SYNOPSIS
 #include <unistd.h>

 unsigned int alarm(unsigned int seconds);

DESCRIPTION
 alarm()  arranges for a SIGALRM signal to be delivered to the 
 calling process in sec‐ onds seconds.

 If seconds is zero, any pending alarm is canceled.
 In any event any previously set alarm() is canceled.

RETURN VALUE
 alarm() returns the number of seconds remaining until any previously
  scheduled  alarm was due to be delivered, or zero if there was 
  no previously scheduled alarm.

一个demo

#include <stdio.h>
#include <unistd.h>

int main()
{

        alarm(5);

        while(1);


        return 0;
}

在这里插入图片描述

4.pause

NAME
   pause - suspend the thread until a signal is received

SYNOPSIS
   #include <unistd.h>

   int pause(void);

DESCRIPTION
   The  pause()  function  shall  suspend  the calling thread until
    delivery of a signal whose action is either to execute a 
    signal-catching  function  or  to  terminate  the  process.

   If the action is to terminate the process, pause() shall not return.
   If  the  action  is to execute a signal-catching function, 
   pause() shall return after  the signal-catching function returns.

5.一个简单的demo的流量控制 漏桶实现

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>


void AlarmHandler(int nNum)
{
        alarm(1);

}


int main(int argc, char **argv)
{
        int fd;
        char Buf[255];
        int RealSize;


        if(argc < 2)
        {
                fprintf(stderr, "No enough argc\n");
                exit(1);
        }

        fd = open(argv[1], O_RDONLY );
        if(fd < 0)
        {
                perror("open()");
                exit(1);
        }

        signal(SIGALRM, AlarmHandler);

        alarm(1);

        while(1)
        {
                pause();
                RealSize = read(fd, Buf, 20);
                write(1, Buf, RealSize);
                if(RealSize < 20)
                        break;
        }



        close(fd);

        return 0;
}

版权声明:本文为ZZHinclude原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。