【TOOLS: Linux C语言实现定时 kill 掉某个进程的 APP】

文章目录

    • 背景
      • 1.1.1 C Code 实现
      • 1.1.2 APP 测试函数
      • 1.1.3 测试过程

背景

当前由于在使用 veloce 抓波形的时候,不知道什么时候波形抓取可以完成,这样就经常导致自己一直要到波形的抓取完成才能回家。。。
所以就想实现一个脚本可以定时去kill 掉抓波形的进程(波形的抓取时间预估),奈何本人对CSH 脚本还不是太熟悉,所以就想到使用C语言来实现一个APP。

1.1.1 C Code 实现

#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv)
{
        time_t now = time(NULL);
        time_t due_time;
        char timestr[64];

        if (argc != 3) {
                printf("Usage error, please input DELAY_TIME (s) and PID\n"
                        "Like: s_app 10 8888\n");
                return -1;
        }

        int delay_s = atoi(argv[1]);
        printf("Wait for %d seconds\n", delay_s);
        due_time = now + delay_s;

        int pid = atoi(argv[2]);

        while ((now = time(NULL)) < due_time) {
                sleep(2);
                strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now));
                printf("Current time: %s\n", timestr);
        }

        int sig = SIGKILL;
        int res = kill(pid, sig);
        if (res == 0) {
                printf("Process %d has been killed.\n", pid);
        } else {
                printf("Failed to kill process %d.\n", pid);
                return -1;
        }
#if 0
        system("ps -ef | grep s_app | grep -v grep | awk '{print $2}' | xargs kill -9");
        while (1) {
                printf("current is alive\n");
                sleep(1);
        }
#endif

        return 0;
}

APP的代码实现后,当就需要对其进行验证,

1.1.2 APP 测试函数

#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv)
{
        while (1) {
                printf("current thread is alive\n");
                sleep(5);
        }
        return 0;
}

1.1.3 测试过程

  • 编译命令:
gcc s_app.c -o s_app
gcc test.c -o test
  • 启动测试
[08:00:43] (*^~^*) ~/workbase> ./test&
current is alive
current is alive
current is alive
current is alive
current is alive
current is alive
current is alive

从上面可以看到每个5s中测试程序会有一句打印,

  • 5秒之后kill掉测试程序
[07:59:44] (*^~^*) ~/workbase> ps -ef current is alive
| grep "test"
kernoops    1680       1  0 5月25 ?       00:00:01 /usr/sbin/kerneloops --test
zhugong+ 2826836 2779216  0 19:59 pts/1    00:00:00 ./test
zhugong+ 2826860 2779216  0 19:59 pts/1    00:00:00 grep --color=auto test
[08:00:11] (*^~^*) ~/workbase> ./s_app
Usage error, please input DELAY_TIME (s) and PID
Like: s_app 10 8888
[08:00:16] (*^~^*) ~/workbase> ./s_app 5 2826836
Wait for 5 seconds
Current time: 2023-06-20 20:00:33
Current time: 2023-06-20 20:00:35
Current time: 2023-06-20 20:00:37
Process 2826836 has been killed.

在另外一个端口也可也看到 test 集成被kill掉了

[07:59:59] (*^~^*) ~/workbase> current is alive
current is alive
current is alive
current is alive
current is alive
current is alive
current is alive
current is alive

[1]+  Killed  

你可能感兴趣的:(Tools,linux,c语言,运维)