简体   繁体   中英

writing to pipe signals synchronization

Here's what I'd like to do: (It is a part of the bigger assignment) And I'm stuck at the start of it.

I've created the main process which forks p1,p2 processes and used execlp(separate programs). They're are supposed to read one word per line from p1.txt (process p1) and p2.txt (process p2) and write it to the pipe. Then in the main process, proc_pr is forked (I don't have the source code for it) , which should send SIGUSR 1 to them whenever it wishes to read a word from pipe and then writes it to the second pipe.

I've tried to come up with simple code in p1, but it does not work most of the time, only in some cases. I could tell from the output of proc_pr that it sent the signal to p1 and then nothing happens. I've seen the solution using the open(),read() and lseek() but I used fopen() and fgets(). Any help is appreciated.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#define MAXLENGTH 150               //definujme si maximalnu dlzku retazca

int fd; int data_processed;         //file deskriptor a premenna na pocitanie precitanych dat
char buff[150];                 //buffer
FILE *f;                    //smernik na prud suboru

/* odchytenie signalu, subor je uz otvoreny a fd nacitany */
void odchytenie(int sig)
{   
    /* read a line */
    if ( fgets ( buff, sizeof buff, f ) != NULL ) 
       {        
             /* write the line */
            fputs ( buff, stdout ); 

            /* store the word into pipe */
           write(fd,buff,strlen(buff));
       } 
       else 
        {
            //do something to stop the process and close the file
        }      

}

int main(int argc, char *args[])
{

 /* prevedieme retazec z parametra na cislo deskriptora pipe na zapis */
 fd = atoi(args[1]);

 /* otvorime subor p1 */
 f=fopen("p1.txt","r");

/* zabezpeci odchytenie signalu */
(void) signal(SIGUSR1,odchytenie);

/* pocka na signal, proces sa neukonci, ani sa nezavrie subor */
while(1) 
 {
    sleep(1);       
 } 

 /* close the file */ 
 fclose(f);

 /* exit with value 0 */
 exit(0);

}

Hm, I've figured it out. The problem was in the main process. And I should probably use async-safe functions in handler.

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