UNIX/Linux:向进程发信号的3种方式

来源:互联网 发布:惠州博罗网络问政 编辑:程序博客网 时间:2024/06/06 18:09

问:怎么向另一个进程发信号?你能跟我解释下在UNIX/Linux环境向一个进程发信号的所有

可用的选项吗?

Answer: You can send various signals to processes using one of the methods explains in this article.

答:你可以用本文所说的任一种方法向进程发各种信号。

1. Send Signal to a Process Using Kill

1.用Kill向进程发信号

Use kill command to send a signal to a process. For example, if you want to send USR1 signal to the process “a.out”, do the following.

使用kill命令向进程发信号。例如,你想向进程“a.out”发送USR1信号,如下所示。

$ ps -C a.out

  $ ps -C a.out

  PID TTY          TIME CMD

    PID TTY           TIME CMD

3699 pts/1    00:00:00 a.out

   3699 pts/1   00:00:00 a.out

$ kill -s USR1 3699

  $ kill -s USER1 3699

Note: Refer to 4 Ways to Kill a Process – kill, killall, pkill, xkill.

注意:参考杀死进程的4种方式-kill,killall,pkill,xkill

2. Send Signal to a Process from Another Process

2.从另一个进程给一个进程发信号

You can use the UNIX system call kill (from a C program) to send signal from one process to another. The following C code snippet shows how to use the kill command.

你可以使用UNIX系统调用kill(从一个C程序)从一个进程给另一个进程发信号。下面的C代码段说明怎样使用kill命令。

Kill system call takes two arguments: 1) the PID (process id) of the process that needs to be signalled 2) the signal that needs to be send to the process. Kill command returns 0 when it is successful. 

Kill系统调用接收两个参数: 1) 需要接收信号的进程PID(进程id) 2)需要发送给进程的信号。调用成功,kill命令返回0。

int send_signal (int pid)

   int send_signal (int pid)

{

   {

        int ret;

           int ret;

        ret = kill(pid,SIGHUP);

           ret = kill(pid, SIGHUP);

        printf("ret : %d",ret);

           printf("ret:%d",ret);

 }

3. Send Signal to a Process from Keyboard

}

3.从键盘给进程发信号

When a process is running on the terminal, you can send signal to that process from the keyboard by using some specific combination of keys. The following are couple of examples.

当一个进程在终端上运行,你可以在键盘上通过按一些特定的组合键来给该进程发信号。下面是两个例子。

■SIGINT (Ctrl + C) – You know this already. Pressing Ctrl + C kills the running foreground process. This sends the SIGINT to the process to kill it. 

   *SIGINT(Ctrl + C) - 你已经知道这个信号。按“Ctrl + C”杀死正在运行的前台进程。这样发送SIGINT信号给进程杀死它。

■You can send SIGQUIT signal to a process by pressing Ctrl +  or Ctrl + Y

   * 通过按“Ctrl + ”或“Ctrl + Y”给进程发SIGQUIT信号

You can view the key mappings that sends specific signal to a process using the “stty -a” command as shown below.

你可以如下所示使用“stty -a”命令查看给进程发送特定信号的键映射。

$ stty -a | grep intr

  $ stty -a | grep intr

intr = ^C; quit = ^; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?;

   intr = ^C; quit = ^; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?;