[cs631apue] questions for our last class

Jan Schaumann jschauma at stevens.edu
Tue Dec 3 13:57:51 EST 2019


Hem Shah <hshah42 at stevens.edu> wrote:

>   1.  If I want to have the same signal handler for
>   all the signals, is there a way to register all
>   signals with 1 call or do we need to register each
>   signal with the signal handler?

You can't ignore or catch _all_ signals: SIGKILL and
SIGSTOP will always be delivered.

If you want to ignore all signals except for those,
then you could use sigprocmask(2):

sigset_t mask;
if (sigfillset(&mask) < 0) {
	fprintf(stder, "Unable to sigfillset: %s\n", strerror(errno));
	exit(EXIT_FAILURE);
}
if (sigprocmask(SIG_SETMASK, &mask, NULL) < 0) {
	fprintf(stder, "Unable to sigprocmask: %s\n", strerror(errno));
	exit(EXIT_FAILURE);
}

Several other signals _should_ not be ignored or
caught, since once they occur, you are by definition
in undefined behavior and cannot rely on anything
continuing to work (e.g., SIGILL upon divide by zero,
or SIGFPE, SIGBUS, SIGSEGV etc.).

If you want to install the same signal handler for
multiple signals, though, you'll need to iterate over
the list of signals you want to catch and call
signal(3) for each.

>   2.  What would be the optimum way to generate
>   random numbers on our system, since during the
>   SIGGOT practise, I got the same sequence of random
>   numbers.

You need to ensure to seed the PRNG at startup.  For
many cases it's sufficient to use e.g., the current
time as a seed:

srand(time(NULL));
printf("Here's a random number between 0 and %d: %d\n", RAND_MAX, rand());
printf("Here's a random number between 0 and 10: %d\n", rand() % 10);

But as noted in the manual page, this is a bad random
number generator.  A better approach is shown in the
file rand.c from lecture 11 (link against libcrypto).

-Jan


More information about the cs631apue mailing list