Pregunta

En Linux, es posible desactivar la señalización de alguna manera para los programas externamente ... es decir, sin modificar su código fuente?

Contexto:

Voy a llamar a un C ( y también un Java) programa desde dentro de un script bash en Linux. No quiero ningún tipo de interrupciones para mi escritura del golpe, y para los otros programas que se lance el script (como procesos en primer plano).

Mientras que puedo usar un ...

trap '' INT

... en mi escritura del golpe para desactivar la señal C Ctrl, esto sólo funciona cuando el control del programa pasa a ser en el código bash. Es decir, si presiono Ctrl C, mientras que el programa de C está en marcha, el programa C se interrumpe y se sale! Este programa C está haciendo alguna operación crítica, debido a lo cual no quiero ser interrumpido. No tengo acceso al código fuente de este programa C, por lo que el manejo dentro del programa de C señal está fuera de cuestión.

#!/bin/bash

trap 'echo You pressed Ctrl C' INT 

# A C program to emulate a real-world, long-running program,
# which I don't want to be interrupted, and for which I 
# don't have the source code!
#
# File: y.c
# To build: gcc -o y y.c
#
# #include <stdio.h>
# int main(int argc, char *argv[]) {
#  printf("Performing a critical operation...\n");
#    for(;;); // Do nothing forever.
#  printf("Performing a critical operation... done.\n");
# }

./y

Saludos,

/ HS

¿Fue útil?

Solución

The process signal mask is inherited across exec, so you can simply write a small wrapper program that blocks SIGINT and executes the target:

#include <signal.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
        sigset_t sigs;

        sigemptyset(&sigs);
        sigaddset(&sigs, SIGINT);
        sigprocmask(SIG_BLOCK, &sigs, 0);

        if (argc > 1) {
                execvp(argv[1], argv + 1);
                perror("execv");
        } else {
                fprintf(stderr, "Usage: %s <command> [args...]\n", argv[0]);
        }
        return 1;
}

If you compile this program to noint, you would just execute ./noint ./y.

As ephemient notes in comments, the signal disposition is also inherited, so you can have the wrapper ignore the signal instead of blocking it:

#include <signal.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
        struct sigaction sa = { 0 };

        sa.sa_handler = SIG_IGN;
        sigaction(SIGINT, &sa, 0);

        if (argc > 1) {
                execvp(argv[1], argv + 1);
                perror("execv");
        } else {
                fprintf(stderr, "Usage: %s <command> [args...]\n", argv[0]);
        }
        return 1;
}

(and of course for a belt-and-braces approach, you could do both).

Otros consejos

The "trap" command is local to this process, never applies to children.

To really trap the signal, you have to hack it using a LD_PRELOAD hook. This is non-trival task (you have to compile a loadable with _init(), sigaction() inside), so I won't include the full code here. You can find an example for SIGSEGV on Phack Volume 0x0b, Issue 0x3a, Phile #0x03.

Alternativlly, try the nohup and tail trick.

nohup  your_command &
tail -F nohup.out

I would suggest that your C (and Java) application needs rewriting so that it can handle an exception, what happens if it really does need to be interrupted, power fails, etc...

I that fails, J-16 is right on the money. Does the user need to interract with the process, or just see the output (do they even need to see the output?)

The solutions explained above are not working for me, even by chaining the both commands proposed by Caf.

However, I finally succeeded in getting the expected behavior this way :

#!/bin/zsh
setopt MONITOR
TRAPINT() { print AAA }

print 1
( ./child & ; wait)
print 2

If I press Ctrl-C while child is running, it will wait that it exits, then will print AAA and 2. child will not receive any signals.

The subshell is used to prevent the PID from being shown.

And sorry... this is for zsh though the question is for bash, but I do not know bash enough to provide an equivalent script.

This is example code of enabling signals like Ctrl+C for programs which block it.

fixControlC.c

#include <stdio.h>
#include <signal.h>
int sigaddset(sigset_t *set, int signo) {
    printf("int sigaddset(sigset_t *set=%p, int signo=%d)\n", set, signo);
    return 0;
}

Compile it:

gcc -fPIC -shared -o fixControlC.so fixControlC.c

Run it:

LD_LIBRARY_PATH=. LD_PRELOAD=fixControlC.so mysqld
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top