简体   繁体   中英

How accurate are kill and signal?

Testing some POSIX codes, I have noticed that the utilisation of signals is not very accurate. 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. 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)?

NB: To execute the code of the client, you have to write the server's PID in command-line arguments.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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