前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux使用KILL 0检测进程是否存在

Linux使用KILL 0检测进程是否存在

作者头像
typecodes
发布2024-03-29 14:35:11
800
发布2024-03-29 14:35:11
举报
文章被收录于专栏:typecodestypecodes

之前遇到过kill( pid, 0 )的情况,由于平常没注意到kill函数的形参为0的情况,不知道它的作用。后面用man 2 kill命令查看了下kill函数的说明,发现可以用来检测进程的存在情况。

man 2 kill查看关于形参0的说明
man 2 kill查看关于形参0的说明
1 关于kill 0的说明1

从上图DESCRIPTION区域的文字可以看出,kill函数中的形参sig是0的话,那么不会向pid进程发送任何信号,但是仍然会继续检测错误(进程ID或者进程组ID是否存在)。kill函数的返回值和具体的错误信息如下:

代码语言:javascript
复制
RETURN VALUE
       On  success  (at least one signal was sent), zero is returned.  On error, -1
       is returned, and errno is set appropriately.

ERRORS
       EINVAL An invalid signal was specified.

       EPERM  The process does not have permission to send the signal to any of the
              target processes.

       ESRCH  The  pid  or  process  group  does  not exist.  Note that an existing
              process might be a zombie, a process which already committed termina‐
              tion, but has not yet been wait(2)ed for.
2 简单测试程序

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

/** * @FileName chk_signal_exist.c * @Describe A simple example for checking if a proccess is existing in linux. * @Author vfhky 2016-03-14 11:48 https://typecodes.com/cseries/kill0checkprocessifexist.html * @Compile gcc chk_signal_exist.c -o chk_signal_exist */ #include <stdio.h> #include <signal.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #define GO_FREE(p) \ free(p); \ p = NULL; \ printf( "exit.\n" ); int main( int argc, char **argv ) { if( argc != 2 ) { printf( "Usage: %s %s\n", argv0, "pid" ); exit(-1); } char *p = (char *)malloc( sizeof(char) * 20 ); memcpy( p, argv1, strlen(argv1) ); /** * no signal is sent, but error checking is still performed; * this can be used to check for the existence of a process ID or process group ID. */ if( kill( atoi(p), 0 ) == -1 ) { perror( "error" ); } else { printf( "Signal%s exist.\n", p ); } GO_FREE(p); return 0; }

3 测试执行

使用《Linux C/C++工程中可生成ELF、动/静态库文件的通用Makefile》一文中的Makefile文件进行程序编译,当然也可以使用命令进行编译gcc chk_signal_exist.c -o chk_signal_exist

先测试进程不存在的情况:随便输入一个进程ID(23232)作为参数1

使用kill 0测试进程不存在的情况
使用kill 0测试进程不存在的情况

然后测试进程存在的情况:先使用ps命令查看已存在的进程daemon_sleep1(20608),然后把作为参数1传入

使用kill 0测试进程存在的情况
使用kill 0测试进程存在的情况
4 其它说明

网上有资料说0代表的是信号0,但是使用命令kill -l却没有显示,所以这里个人觉得不应该叫信号0。它只是kill函数中的一个普通形参而已,大于0的时候发送对应信号给某个进程,等于0的时候表示检测某个进程是否存在。

kill -l命令查看所有支持的信号
kill -l命令查看所有支持的信号
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-03-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 关于kill 0的说明1
  • 2 简单测试程序
  • 3 测试执行
  • 4 其它说明
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档