Simple synchronization with C signals

这一生的挚爱 提交于 2021-02-05 06:40:31

问题


I'm trying to solve an exercise which requires that : "the starting process must fork two times. The father and the children must synchronize to write, one after another, in the first position of a temporary file reading the characters written on three different files (one for each process). The program must use signals to implement the synchronization mechanism."

So far i've tried to solve this by doing so :

  • P1 (the father) starts reading/writing first. Before stopping himself (through a call to the raise function), he sends a SIGCONT signal to wake up F2 (the second child)
  • F2 reads from his file and writes on the temp file. He then stops himself too, and sends a SIGCONT signal to wake up F1 (the first child)
  • F1 does the same as F2, but wakes up P1 and so on...

However, i can't get the code working (in some cases, after changing the order of the readings and writings, i got most of the latter in output but the program behavior was always erratic and never terminated).

Here's my code :

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

#define TEMP_PATH "/tmp/mytempfile"

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

FILE *writeFp;
FILE *rfpF1;
FILE *rfpF2;
FILE *rfpP1;
pid_t pid1, pid2;

char car;   
char sizeOfChar = sizeof(char);

if (argc != 4 || !strcmp(argv[1], "--help")){
    fprintf(stderr, "Usage : %s filePath1 filePath2 filePath3\n", argv[0]);
    exit(EXIT_FAILURE);
}

if (access(argv[1], F_OK)==-1){
    perror("access 1 error");
    exit(EXIT_FAILURE);
}

if (access(argv[2], F_OK)==-1){
    perror("access 2 error");
    exit(EXIT_FAILURE);
}

if (access(argv[3], F_OK)==-1){
    perror("access 3 error");
    exit(EXIT_FAILURE);
}

if((writeFp = fopen(TEMP_PATH, "w")) == NULL){
    fprintf(stderr, "Can't open temp file on writing.\n");
    exit(EXIT_FAILURE);
}

if ((rfpP1 = fopen(argv[3], "r")) == NULL){
    fprintf(stderr, "Can't open %s on reading.\n", argv[3]);
    exit(EXIT_FAILURE);
}   

switch(pid1 = fork()){
    case -1:
            perror("fork error");
            exit(EXIT_FAILURE);

    case 0:
            /* F1 : first child */

            if ((rfpF1 = fopen(argv[1], "r")) == NULL){
                fprintf(stderr, "Can't open %s on reading.\n", argv[1]);
                exit(EXIT_FAILURE);
            }

            raise(SIGSTOP);
            while(fscanf(rfpF1, "%c", &car) != EOF){

                if(fseek(writeFp, 0L, SEEK_SET) == -1){
                    perror("fseek error");
                    exit(EXIT_FAILURE);
                }
                if(fprintf(writeFp, "%c", car) != 1){
                    fprintf(stderr, "fprintf error. Terminating...\n");
                    exit(EXIT_FAILURE);
                }                   

                if(kill(getppid(), SIGCONT) == -1){
                    perror("F1 kill error");
                    exit(EXIT_FAILURE);
                }

                printf("F1 : i've written '%c'\n", car); fflush(stdout);

                // If with the next read EOF is reached, the process doesn't have to stop...
                if(fscanf(rfpF1, "%c", &car) == EOF)
                    break;
                else{
                    if(fseek(rfpF1, -sizeOfChar, SEEK_CUR)){
                        perror("fseek error");
                        exit(EXIT_FAILURE);
                    }
                    raise(SIGSTOP);
                }
            }

            fclose(rfpF1);              
            exit(EXIT_SUCCESS);


    default :
            break;  

}


switch(pid2 = fork()){
    case -1:
            perror("fork 2 error");
            exit(EXIT_FAILURE);

    case 0:
            /* F2 : second child */

            if ((rfpF2 = fopen(argv[2], "r")) == NULL){
                fprintf(stderr, "Can't open %s on reading.\n", argv[2]);
                exit(EXIT_FAILURE);
            }

            raise(SIGSTOP);
            while(fscanf(rfpF2, "%c", &car) != EOF){

                if(fseek(writeFp, 0L, SEEK_SET) == -1){
                    perror("fseek error");
                    exit(EXIT_FAILURE);
                }
                if(fprintf(writeFp, "%c", car) != 1){
                    fprintf(stderr, "fprintf error. Terminating...\n");
                    exit(EXIT_FAILURE);
                }               

                if(kill(pid1, SIGCONT) == -1){
                    perror("F2 kill error");
                    exit(EXIT_FAILURE);
                }

                printf("F2 : i've written '%c'\n", car); fflush(stdout);

                if(fscanf(rfpF2, "%c", &car) == EOF)
                    break;
                else{
                    if(fseek(rfpF2, -sizeOfChar, SEEK_CUR)){
                        perror("fseek error");
                        exit(EXIT_FAILURE);
                    }
                    raise(SIGSTOP);
                }
            }

            fclose(rfpF2);  
            exit(EXIT_SUCCESS);
    default:    
            /* P1 : Father */

            // Wait for the children to be interrupted by SIGSTOP (which changes their states)
            if(wait(NULL) == -1){
                perror("wait 1 error");
                exit(EXIT_FAILURE);
            }

            if(wait(NULL) == -1){
                perror("wait 2 error");
                exit(EXIT_FAILURE);
            }

            // P1 is the first to be reading and writing...
            while(fscanf(rfpP1, "%c", &car) != EOF){

                if(fseek(writeFp, 0L, SEEK_SET) == -1){
                    perror("fseek error");
                    exit(EXIT_FAILURE);
                }
                if(fprintf(writeFp, "%c", car) != 1){
                    fprintf(stderr, "fprintf error. Terminating...\n");
                    exit(EXIT_FAILURE);
                }

                if(kill(pid2, SIGCONT) == -1){
                    perror("P kill error");
                    exit(EXIT_FAILURE);
                }

                printf("P1 : i've written '%c'\n", car); fflush(stdout);

                if(fscanf(rfpP1, "%c", &car) == EOF)
                    break;
                else{
                    if(fseek(rfpP1, -sizeOfChar, SEEK_CUR)){
                        perror("fseek error");
                        exit(EXIT_FAILURE);
                    }
                    raise(SIGSTOP);
                }

            }

            fclose(rfpP1);  
            break;
}

// Wait for the children...
if(wait(NULL) == -1){
    perror("wait 1 error");
    exit(EXIT_FAILURE);
}

if(wait(NULL) == -1){
    perror("wait 2 error");
    exit(EXIT_FAILURE);
}

fclose(writeFp);
exit(EXIT_SUCCESS);
}

回答1:


A better way to-do this would be to utilize the sigwait() function with a signal mask set to the signal you want to wait on. First, before you can use sigwait(), you should make sure that the signal you are waiting on is first blocked in the signal mask of the process or thread. Then, do the following:

  1. In the parent, open all the appropriate file descriptors for the files you're going to be reading and writing from
  2. Set the signal mask of the parent process so that you're blocking the signal you're going to be using for synchronization between the parent and child processes.
  3. Fork the child processes. After setting up the processing, in a while-loop, call sigwait() with a signal mask that only includes the synchronization signal. When the synchronization signal is received by that child process, it will continue through the while-loop. Before completing the loop and repeating the blocking call to sigwait(), send a signal to the next process.
  4. In the parent process, using a while-loop do the first read/write sequence, and then send a signal to the next child process. Finally, call sigwait() at the end of the loop.

So in the end your child processes would look something like:

//child process

//...setup the child process

while (/* some condition for stopping */)
{
    int signal
    sigwait(&signal_mask, &signal)

    //check to make sure we're getting the right signal
    if (signal != synchronization_signal)
        continue;

    //...more code for reading/writing to files

    //send a signal to next process in-line
    //i.e., F1 will send a signal to F2, and F2 will signal P1    
}

and your parent process would look like:

//...block the synchronization signal and fork the children

while (/* some condition for stopping */)
{
    //...perform the reading and writing to the files

    //send signal to F1

    //block waiting for the signal to arrive from F2
    while (true)
    {
        int signal;
        sigwait(&signal_mask, &signal);

        //check to make sure we're getting the right signal
        if (signal == synchronization_signal)
            break;
    }
}   


来源:https://stackoverflow.com/questions/8702966/simple-synchronization-with-c-signals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!