使用c中的警报同步进程

时间:2016-03-12 01:04:40

标签: c process signals alarm

我必须写一个关于信号和警报的程序,我不能使用信号量 第一个进程(名为“B”)启动另一个进程(名为“A”)。 “A”必须在文件中写入随机单词,每5秒写一次,如果写入单词END则终止执行。进程“B”必须从文件中读取单词,如果读取END则重新启动进程“A”。当“B”读取50个单词时会杀死“A”并终止执行

该程序无法正常运行,我认为这是因为两个进程同时访问该文件,但我不确定

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

#define SECS 5
#define MAX_READ 50
#define MAX_TAM 10
#define N_WORDS 13

int main(void){
    int i=0,flag;
    pid_t pid;
    static char words[][MAX_TAM]={"THE","PROCESS","A","WRITES","IN","A","FILE","WORDS","AND","KILL","ITSELF","WITH","END"};
    char *word; 
    char read[MAX_TAM];
    FILE *fp=fopen("file2.txt","w");
    if(!fp){
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }

    if (signal(SIGALRM, SIG_IGN) == SIG_ERR){
        puts("Error");
        exit (EXIT_FAILURE);
    }
    while(1){
        flag=0;
        switch(pid=fork()){
            case -1:
                perror("fork error");
                exit(EXIT_FAILURE);
            case 0: /* A  */
                srand(getpid());
                while(1){
                    if(alarm(SECS))
                        pause();       
                    word = words[rand()%N_WORDS];       
                    fprintf(fp,"%s ",word);
                    printf("A ~ WORD: %s\n",word);
                    fflush(stdout);
                    if(!strcmp(word,"END")){
                        fclose(fp);
                        printf("ENDING A\n");
                        exit(EXIT_SUCCESS);
                    }       
                }
            default: /* Proceso B */
                sleep(1);
                for( ;i<MAX_READ;i++){
                    if(alarm(SECS))
                        pause();
                    fscanf(fp,"%s",read);
                    printf("B ~ READING %s\n",read);
                    fflush(stdout);
                    if(!strcmp(read,"END")){
                        flag=1;
                        break;
                    }
                }
        }
        if(flag==0)
            break;
    }
    kill(pid,9);
    exit(EXIT_SUCCESS);
}

0 个答案:

没有答案