The signal handler will not see the global variable

Here's the problem: this program should receive input from stdin and count the input bytes; the SIGUSR1 signal stops the main program and will print a standard file error, how many bytes were copied when sending SIGUSR1.

How my teacher wants me to do this: in one terminal type

cat /dev/zero | ./cpinout | cat >/dev/null

and signals are sent from the second terminal using

kill -USR1 xxxx

where xxxx is the pid cpinout.

I updated my previous code:

/* cpinout.c */

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

#define BUF_SIZE 1024   

volatile sig_atomic_t countbyte = 0;
volatile sig_atomic_t sigcount = 0;

/* my_handler: gestore di signal */
static void sighandler(int signum) {
    if(sigcount != 0)
        fprintf(stderr, "Interrupted after %d byte.\n", sigcount);
    sigcount = contabyte;
}

int main(void) {

    int c;
    char buffer[BUF_SIZE];
    struct sigaction action;

    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    action.sa_handler = sighandler;
    if(sigaction(SIGUSR1, &action, NULL) == -1) {
        fprintf(stderr, "sigusr: sigaction\n");
        exit(1);
    }
    while( c=getc(stdin) != EOF ) {
        countbyte++;
        fputc(c, stdout);
    }
    return(0);
}
+5
source share
2 answers


EDIT

In the comments, you mentioned that you use the command as:

cat /dev/zero | ./namefile | cat >/dev/null

. /dev/zero - , . , . , , .


, ( ). GNU , , int POSIX.

, , , fputc printf (, , printf , ). fputc , , .

EDIT:

. , :

, . stdio (printf(), scanf(), ..), -. , printf() - - printf() stdio. ( Linux)

stdio, , , .


:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

int countbyte = 0;  // for main program
int sigcount = 0;   // for signal handler

/* my_handler: signal handler */
static void sighandler(int signum)
{
   sigcount = countbyte;
}

int main(void)
{ 
   int c;
   struct sigaction sigact;

   sigemptyset(&sigact.sa_mask);
   sigact.sa_flags = 0;
   sigact.sa_handler = sighandler;
   sigaction(SIGUSR1, &sigact, NULL);
   while ((c = getc(stdin)) != EOF) {
      countbyte++;
      fputc(c, stdout);
   }
   if (sigcount != 0) {
      printf("Interrupted after %d bytes\n", sigcount);
   }

   return 0;
}
+2

volatile sig_atomic_t C89 POSIX 7:

undefined, [CX] [Option Start], errno [Option End] , , volatile sig_atomic_t

, , printf - , .

+3

All Articles