简体   繁体   English

杀戮和信号有多准确?

[英]How accurate are kill and signal?

Testing some POSIX codes, I have noticed that the utilisation of signals is not very accurate. 测试一些POSIX代码,我注意到信号的利用率不是很准确。 Here is a sample code of the client: 以下是客户端的示例代码:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#define MESSAGE "hello\n"
#define PAUSE   15000

int main(int argc, char **argv)
{
    int pid = atoi(argv[1]);
    size_t i;
    int j;

    for (i = 0; i < sizeof MESSAGE; ++i) {
        for (j = 0; j < MESSAGE[i]; ++j) {
            kill(pid, SIGUSR1);
            usleep(PAUSE);
        }
        kill(pid, SIGUSR2);
        usleep(PAUSE);
    }
    return 0;
}

Here is the code of the server: 这是服务器的代码:

#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

static unsigned char index;

static void inc(int sig)
{
    ++index;
    (void) sig;
}

static void prt(int sig)
{
    printf("%c", index);
    fflush(stdout);
    index = 0;

    (void) sig;
}

int main(void)
{
    printf("%ld\n", (long int)getpid());

    signal(SIGUSR1, inc);
    signal(SIGUSR2, prt);

    for (;;)
        ;

    return 0;
}

The characters received by the server depends on what PAUSE value has the client. 服务器接收的字符取决于客户端的PAUSE值。 Does it come from signals' limits, or did I commit an error? 它是来自信号的限制,还是我犯了错误? If so, where could I find these environmental considerations (I use Linux 2.6.35)? 如果是这样,我在哪里可以找到这些环境因素(我使用Linux 2.6.35)?

NB: To execute the code of the client, you have to write the server's PID in command-line arguments. 注意:要执行客户端代码,必须在命令行参数中编写服务器的PID。

Not only is this sort of inter-process communication incredibly inefficient; 这种进程间通信不仅非常低效; it's also invalid. 它也无效。 Signals are not queued; 信号没有排队; they're either pending or non-pending (*). 他们要么待定也要等待(*)。 So unless the recipient process reads off the signal before the sender sends another one, signals will be lost. 因此,除非接收方进程在发送方发送另一个之前读取信号,否则信号将丢失。

If you really want to do something hideous like this, the recipient needs to acknowledge each signal it receives by signalling back to the sender, and the sender needs to wait to send the next signal until the previous one was acknowledged. 如果你真的想做一些像这样可怕的事情,收件人需要通过发信号通知发送方来确认收到的每个信号,并且发送方需要等待发送下一个信号,直到确认上一个信号。

(*) Actually, real-time signals are queued, but the depth of the queue has a limit, and ensuring that it doesn't overrun would require painful and fragile realtime-priority-management logic. (*)实际上, 实时信号是排队的,但队列的深度有一个限制,并确保它不会溢出将需要痛苦和脆弱的实时优先级管理逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM