我编写了以下脚本,如果grep在文件中找不到相关的字符串,则该超时时间为20秒。
脚本运行良好,但是脚本的输出如下:
./test: line 11: 30039: Killed
如何通过kill命令禁用此消息?
如何告诉kill命令忽略进程是否不存在?
THXYael
#!/bin/ksh
( sleep 20 ; [[ ! -z ` ps -ef | grep "qsRw -m1" | awk '{print $2}' ` ]] && kill -9 2>/dev/null ` ps -ef | grep "qsRw -m1" | awk '{print $2}' ` ; sleep 1 ) &
RESULT=$!
print "the proccess:"$RESULT
grep -qsRw -m1 "monitohhhhhhhr" /var
if [[ $? -ne 0 ]]
then
print "kill "$RESULT
kill -9 $RESULT
fi
print "ENDED"
./test
the proccess:30038
./test: line 11: 30039: Killed
kill 3003
kill -9 $RESULT &> /dev/null
这会将stdout
和stderr
发送到/ dev / null。
您最好看看timeout
命令
man timeout
NAME
timeout - run a command with a time limit
SYNOPSIS
timeout [OPTION] NUMBER[SUFFIX] COMMAND [ARG]...
timeout [OPTION]
DESCRIPTION
Start COMMAND, and kill it if still running after NUMBER seconds. SUFFIX may be `s' for
seconds (the default), `m' for minutes, `h' for hours or `d' for days.
消息是由您的外壳打印的,而不是由终止进程打印的。
尝试运行要在另一个外壳中杀死的过程,将被杀死的命令封装如下:
sh -c 'command_to_be_inettrupted&'
想法是使shell实例比启动它的进程更早退出。您可能还需要“ nohup”命令,但这在我的系统上是不必要的。
例如:
sh -c 'sleep 10&' ; sleep 1; killall sleep
尽管第一个睡眠实例被杀死,但是此代码不会产生任何输出。
我认为此消息来自作业控制。尝试使用set + m将其关闭如果在ksh下不起作用,请尝试使用#!/ bin / bash
脚本。用C编程:
/* Kill process without printing 'Killed' or 'Terminated' message. */
kill(pid, SIGINT);
或
execl("/bin/bash", "bash", "-c", "kill -SIGINT `pidof <your command>` >/dev/null 2>&1", (char *)NULL);
killpid.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
/*
$ gcc -W -Wall -O3 -std=c99 -pedantic -o killpid killpid.c
*/
#define LEN 10
int main()
{
char line[LEN] = {0};
FILE *cmd = popen("pidof <your command>", "r");
fgets(line, LEN, cmd);
pid_t pid = strtoul(line, NULL, 10);
printf("pid: %ld\n", pid);
/* Kill process without printing 'Killed' or 'Terminated' message.*/
kill(pid, SIGINT);
pclose(cmd);
return 0;
}
通过kill命令:
$ kill -SIGINT `ps -ef | grep <your command> | awk '{print $2}'` >/dev/null 2>&1
或
$ kill -SIGINT `pidof <your command>`