Posted on 2009-02-17 17:50
Prayer 閱讀(6138)
評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi):
LINUX/UNIX/AIX
kill(傳送信號(hào)給指定的進(jìn)程)
表頭文件
#include<sys/types.h>
#include<signal.h>
定義函數(shù) int kill(pid_t pid,int sig);
函數(shù)說(shuō)明
kill()可以用來(lái)送參數(shù) sig 指定的信號(hào)給參數(shù) pid 指定的進(jìn)程。參數(shù) pid 有幾種情況:
pid>0 將信號(hào)傳給進(jìn)程識(shí)別碼為 pid 的進(jìn)程。
pid=0 將信號(hào)傳給和目前進(jìn)程相同進(jìn)程組的所有進(jìn)程
pid=-1 將信號(hào)廣播傳送給系統(tǒng)內(nèi)所有的進(jìn)程
pid<0 將信號(hào)傳給進(jìn)程組識(shí)別碼為 pid 絕對(duì)值的所有進(jìn)程
返回值 執(zhí)行成功則返回 0,如果有錯(cuò)誤則返回-1。
EINVAL 參數(shù) sig 不合法
錯(cuò)誤代碼 ESRCH 參數(shù) pid 所指定的進(jìn)程或進(jìn)程組不存在
EPERM 權(quán)限不夠無(wú)法傳送信號(hào)給指定進(jìn)程
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main( void )
{
pid_t childpid;
int status;
int retval;
childpid = fork();
if ( -1 == childpid )
{
perror( "fork()" );
exit( EXIT_FAILURE );
}
else if ( 0 == childpid )
{
puts( "In child process" );
sleep( 100 );//讓子進(jìn)程睡眠,看看父進(jìn)程的行為
exit(EXIT_SUCCESS);
}
else
{
if ( 0 == (waitpid( childpid, &status, WNOHANG )))
{
retval = kill( childpid,SIGKILL );
if ( retval )
{
puts( "kill failed." );
perror( "kill" );
waitpid( childpid, &status, 0 );
}
else
{
printf( "%d killed\n", childpid );
}
}
}
exit(EXIT_SUCCESS);
}
[root@localhost src]# gcc killer.c
[root@localhost src]# ./a.out
In child process
4545 killed
在確信fork調(diào)用成功后,子進(jìn)程睡眠100秒,然后退出。
同時(shí)父進(jìn)程在子進(jìn)程上調(diào)用waitpid函數(shù),但使用了WNOHANG選項(xiàng),
所以調(diào)用waitpid后立即返回。父進(jìn)程接著殺死子進(jìn)程,如果kill執(zhí)行失敗,
返回-1,否這返回0。如果kill執(zhí)行失敗,父進(jìn)程第二次調(diào)用waitpid,
保證他在子進(jìn)程退出后再停止執(zhí)行。否則父進(jìn)程顯示一條成功消息后退出。
本文來(lái)自: (www.91linux.com) 詳細(xì)出處參考:http://www.91linux.com/html/article/program/20071017/7635.html