简体   繁体   中英

process sync using sigusr1 and sigusr2

i am writing a producer process to write a block of data to a file, and a consumer process to read the same block, but the below code gets stuck in an infinite loop, now from my side i think i am having a problem in the consumer process implementation!!

void wakeup() { ; };
unsigned int sleep ( unsigned int timer ) 
{
   if (sigset(SIGALRM, wakeup)==-1) {
     perror("sigset"); return 1;
}

        (void)alarm( timer );
        (void)pause();
        return 0;
        }



int main(void) {
int fd, n, i, SomeInt, DataRead;
pid_t pid, ppid; 
char buf[4];
char *buf2;
int x=0;
if((fd=open("/tmp/data_file", O_APPEND|O_CREAT, 0640)) <0) exit(1);
sigset(SIGTERM,SIG_IGN);/* signal */   ; sigset(SIGINT,SIG_IGN); /* signal */ 
pid=fork(); 
switch (pid) { 
    case -1: { perror("FORK"); exit(1); } break;
    case 0: /* child process - Producer */ 
        sigset(SIGUSR1,wakeup);   
        sighold(SIGUSR1);       /* block / hold signals SIGUSR1 until sigpause*/ 

   FILE *file = fopen ("binary.txt", "r");
    while (!feof(file))
     {    n = (int)(getpid()%256); 
          srand((unsigned)n);
          sleep(rand() %5);
          for( x=0; x<=4;x++)
             fscanf (file, "", buf[x]);

         write(fd, buf,sizeof(buf)); 
        ppid=getppid(); 
        kill(ppid, SIGUSR2);   
        sigpause(SIGUSR1); 

      }

   fclose(file);
   fflush(stdin);


break;


default:    /* -parent code - Consumer */ 


                sigset(SIGUSR2,wakeup);
        sighold(SIGUSR2);       /* block / hold signals SIGUSR2 until sigpause*/ 
        for (i=0; i<=100; i++) { 
            /* sleep a random amount of time */ 
            n = (int)(getpid()%256); 
            srand((unsigned)n); 
            sleep(rand() %5);
            sigpause(SIGUSR2); /* pause(); */ 
            /* reads a character from file */ 
            read(fd, buf,sizeof(buf)); 
            fprintf(stderr,"Consumer PID=%d value=%d\n",getpid(),atoi(buf));
            kill(pid, SIGUSR1) ;
} 
break; 
} 
exit(0); 
}

the below code gets stuck in an infinite loop, now from my side i think i am having a problem in the consumer process implementation

One problem is in the producer process, where you programmed an infinite loop as follows:

 while (!feof(file))
 {    ...
      for (x=0; x<=4; x++)
           fscanf(file, "", buf[x]);
      ...
 }

With the empty format string you manage to read nothing from the file, and thus never reaching feof(file) .

Among other serious problems you have are your indentation "style" (as AShelly mentioned) and the lack of error checking (eg of fopen() and write() ).

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