Not able to Display the Catched Signal

my code here is intended to display the received signal that's it but its not working when i try to send the signal
kill -SIGUSR1 pid
or
kill -10 pid
or any other signals according to my program

#include"headers.h"
static void sig_usr(int);
main()
{
        if(signal(SIGUSR1,sig_usr)==SIG_ERR)
                printf("cant catch signal sigusr1");
        if(signal(SIGUSR2,sig_usr)==SIG_ERR)
                printf("cant catch signal sigusr2");
        while(1);
        pause();
}
static void sig_usr(int signo)
{
if(signo==SIGUSR1)
        printf("Rx sigusr1");
else if(signo==SIGUSR2)
        printf("Rx sigusr2");
else printf("recieved signal is %d",signo);
return;
}

so i debugged it
debug results:

Breakpoint 1, main () at catch_signal.c:5
5       if(signal(SIGUSR1,sig_usr)==SIG_ERR)
(gdb) n
7       if(signal(SIGUSR2,sig_usr)==SIG_ERR)
(gdb) n
9       while(1);
(gdb) n

Program received signal SIGUSR1, User defined signal 1.
main () at catch_signal.c:9
9       while(1);
(gdb) n
sig_usr (signo=10) at catch_signal.c:13
13  {
(gdb) n
14  if(signo==SIGUSR1)
(gdb) n
15      printf("Rx sigusr1");
(gdb) n

Program received signal SIGTRAP, Trace/breakpoint trap.
0x08048326 in printf@plt ()
(gdb) n
Single stepping until exit from function printf@plt,
which has no line number information.
0x08048310 in ?? ()
(gdb) n
Cannot find bounds of current function

im supposed to get the result output as Rx signal usr1 but i havnt why so:wall:

Signal 10, as I recall, is bus error, which is no catch but core dump if allowed. Signal 1 is hangup or HUP, very catchable even in scripts. Your man kill, man signal, signal.h will vary:

   signum   signame   Name            Description
   ___________________________________________________________________________
      0     SIGNULL   Null            Check access to pid
      1     SIGHUP    Hangup          Terminate; can be trapped
      2     SIGINT    Interrupt       Terminate; can be trapped
      3     SIGQUIT   Quit            Terminate with core dump; can be trapped
      9     SIGKILL   Kill            Forced termination; cannot be trapped
     15     SIGTERM   Terminate       Terminate; can be trapped
     24     SIGSTOP   Stop            Pause the process; cannot be trapped
     25     SIGTSTP   Terminal stop   Pause the process; can be trapped
     26     SIGCONT   Continue        Run a stopped process
 
signal.h:
 
/* Signal numbers */
#  define _SIGHUP       1       /* hangup */
#  define SIGINT        2       /* Interrupt */
#  define _SIGQUIT      3       /* quit */
#  define SIGILL        4       /* Illegal instruction (not reset when
                                   caught) */
#  define _SIGTRAP      5       /* trace trap (not reset when caught) */
#  define SIGABRT       6       /* Process abort signal */
#  define _SIGIOT       SIGABRT /* IOT instruction */
#  define _SIGEMT       7       /* EMT instruction */
#  define SIGFPE        8       /* Floating point exception */
#  define _SIGKILL      9       /* kill (cannot be caught of ignored) */
#  define _SIGBUS       10      /* bus error */
#  define SIGSEGV       11      /* Segmentation violation */
#  define _SIGSYS       12      /* bad argument to system call */
#  define _SIGPIPE      13      /* write on a pipe with no one to read it */
#  define _SIGALRM      14      /* alarm clock */
#  define SIGTERM       15      /* Software termination signal from kill */
#  define _SIGUSR1      16      /* user defined signal 1 */
#  define _SIGUSR2      17      /* user defined signal 2 */
#  define _SIGCHLD      18      /* Child process terminated or stopped */
#  define _SIGCLD       _SIGCHLD        /* death of a child */
#  define _SIGPWR       19      /* power state indication */
#  define _SIGVTALRM    20      /* virtual timer alarm */
#  define _SIGPROF      21      /* profiling timer alarm */
#  define _SIGIO        22      /* asynchronous I/O */
#  define _SIGPOLL      _SIGIO  /* for HP-UX hpstreams signal */
#  define _SIGWINCH     23      /* window size change signal */
#  define _SIGWINDOW    _SIGWINCH /* added for compatibility reasons */
#  define _SIGSTOP      24      /* Stop signal (cannot be caught or ignored) */
#  define _SIGTSTP      25      /* Interactive stop signal */
#  define _SIGCONT      26      /* Continue if stopped */
#  define _SIGTTIN      27      /* Read from control terminal attempted by a
                                   member of a background process group */
#  define _SIGTTOU      28      /* Write to control terminal attempted by a
                                   member of a background process group */
#  define _SIGURG       29      /* urgent condition on IO channel */
#  define _SIGLOST      30      /* remote lock lost  (NFS)        */
#  define _SIGRESERVE   31      /* Save for future use */
#  define _SIGDIL       32      /* DIL signal */
#  define _SIGXCPU      33      /* CPU time limit exceeded (setrlimit)  */
#  define _SIGXFSZ      34      /* CPU file size limit exceeded (setrlimit)  */
#  define _SIGCANCEL    35      /* Used for pthread cancellation. */
#  define _SIGGFAULT    36      /* Graphics framebuffer fault */
#  define _SIGRTMIN     37      /* First (highest priority) realtime signal */
#  define _SIGRTMAX     44      /* Last (lowest priority) realtime signal */
 

Are you certain that it isn't being printed? Are you running the binary in the background while trying to send signals to it? If so, depending on your terminal settings, an attempt to write to the terminal could stop the process. Also, note that your printf statements do not have a terminating newline. Perhaps it did print but you missed it? Perhaps the output got lost among other output, such as the shell prompt? Depending on how you called it, perhaps its stdout has been redirected?

Your code spins needlessly. while (1); cpu usage will hit 100% and pause() is never reached. You can accomplish your goal without using any cpu between signals: while (1) pause(); or even while (pause());

Regards,
Alister

1 Like

this trick done the thing what does actually happened why adding newlines made a change,can u please elucidate,

what '\n' actually does here,also the process exited why so it must have returned and stay

very thanks

\n tells it to flush the buffer.

Until you print a \n, data just stays in a buffer in memory.

1 Like

STDIO streams are either fully buffered (i.e., the buffer is not flushed until the buffer is full), line buffered (i.e., the buffer is flushed when a complete line is in the buffer or the buffer is full), or unbuffered (i.e., the buffer is flushed whenever there is data in the buffer [usually at the end of a call to a stdio function like putc(), printf(), or fwrite()]). By default, stderr is not fully buffered. By default, stdin and stdout cannot be fully buffered unless the system can determine that the stream is not connected to a TTY device file.

So adding a "\n" to your printf() format string will usually initiate a flush of stdout's buffer before printf() returns to the calling program unless the ouput of the program is redirected to a regular file. You can manually flush the buffer anytime you want to with a call to fflush(stdout), and you can use setvbuf() to change the buffering mode for a stream to any of the three forms of buffering for any open stream.

4 Likes

thanks for ur reply i got an understanding over flushing buffers and their advantage

i did not get this line can u elucidate,what is getting connecting to tty device file

A TTY terminal device is a character device that performs input and output on a character-by-character basis.

The communication between terminal devices and the programs that read and write to them is controlled by the TTY interface. Examples of TTY devices are ASCII terminal and modems.

Back in the old days, when Teletype devices and stand-alone terminals were connected by wires to the back of a shared computer or over a phone line that was connected to a modem that was connected by wires to the back of a shared computer, everyone knew how a terminal appeared as a character special file that supported the general terminal interfaces.

Most vendor man page set will have a termios man page (but the section it is in will vary). Chapter 11 of the Base Definitions volume of the current POSIX standard has more than a dozen pages describing the General Terminal Interface (GTI).

The extremely quick overview, is that any time you have a user typing on a keyboard to interactively enter input into a program and interactively looking at output produced by a program on a screen or typewriter-like device, you are likely using a tty device or pseudo-tty device that behaves mostly as specified by the POSIX GTI. :cool:

It is wise to log debug stuff to stderr, which by default is completely unbuffered. Just change 'printf(' to 'fprintf( stderr,'.

If speed is a focus, don't write bulk to unbuffered or line buffered FILE*'s like stderr, use a well buffered one, see man setvbuf(), some multiple of the disk page or packet size size like 65536 or 57600, less than the system write buffer or socket send buffer size, and fflush() only if necessary.

Calling exit() almost always flushes FILE*'s free of charge, but I had a primitive C compiler once that didn't.

---------- Post updated at 04:47 PM ---------- Previous update was at 04:46 PM ----------

You can use a tool like strace/truss/tusc to trace system calls and signals of the running process to a log file, and see what signals are doing what to your process.

It's also wise because it keeps your error messages separate from your data. If you're writing a PNG image to standard output, for instance, you don't want "Warning: Needed to flatten image" stuck randomly in the middle of that, you want that going where a human will read it or just nowhere. Writing to stderr lets you control it independently.

Good error handling makes for short debug times and happier production support. That is why stderr is always open and unbuffered at the start. Point it at a log file.