之前遇到过kill( pid, 0 )
的情况,由于平常没注意到kill函数的形参为0的情况,不知道它的作用。后面用man 2 kill
命令查看了下kill函数的说明,发现可以用来检测进程的存在情况。
从上图DESCRIPTION区域的文字可以看出,kill函数中的形参sig是0的话,那么不会向pid进程发送任何信号,但是仍然会继续检测错误(进程ID或者进程组ID是否存在)。kill函数的返回值和具体的错误信息如下:
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.
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; } |
---|
使用《Linux C/C++工程中可生成ELF、动/静态库文件的通用Makefile》一文中的Makefile文件进行程序编译,当然也可以使用命令进行编译gcc chk_signal_exist.c -o chk_signal_exist
。
先测试进程不存在的情况:随便输入一个进程ID(23232)作为参数1
然后测试进程存在的情况:先使用ps命令查看已存在的进程daemon_sleep1(20608),然后把作为参数1传入
网上有资料说0代表的是信号0
,但是使用命令kill -l
却没有显示,所以这里个人觉得不应该叫信号0
。它只是kill函数中的一个普通形参而已,大于0的时候发送对应信号给某个进程,等于0的时候表示检测某个进程是否存在。