简体   繁体   中英

Read a file using two processes in linux?

I wrote a program to accomplish this:

process p1 will open a file then p1 will read the file upto certain number of lines there after process p2 will be reading same file there after p1 will be reading and so on till end of file . eg file contains 100 lines then p1 will read 0-10 lines then p2 will read 10-20 then p1 will read 20-30 lines and so on .

code of p1

pid_t cpid;
#define MAXR 5 //Maximum number of rows 
void sigread(int signo){ //When a signal received read MAXR line 
    int i;
    char buf[MAXS];
    cout<<"p1\n";
    for(i=0;i<MAXR;i++){
            cin.getline(buf,MAXS);
            cout<<buf<<"\n";
    }
    signal(signo,sigread); //register signal again
    kill(cpid,SIGUSR2);//send a signal to p2 to read another MAXR line 
}
int main(){
    signal(SIGUSR1,sigread); //register signal handler to this process 
    char buf[MAXS];
    int c=-1;
    fd = open("in.txt",O_RDONLY);
    dup2(fd,0); //duplicate file descriptor to STD_IN


    cpid =  fork();//Create a child process 
    if(cpid<0){
        cout<<"Fork failed\n";
        exit(1);
    }
    if(cpid>0){
        while(1); //run forever 
    }
    else{
        execlp("./p2","p2",NULL); //Use execlp to execute p2
    }
    return 0;
}

//code of p2

void sigread(int signo){
    int i=0;
    char buff[MAXS];
    cout<<"p2\n";
    for(i=0;i<MAXR;i++){
        cin.getline(buff,MAXS);
        cout<<buff<<"\n";
    }
    signal(signo,sigread);
    kill(getppid(),SIGUSR1); //send a signal to p1
}
int main(){
    signal(SIGUSR2,sigread);
    kill(getppid(),SIGUSR1); //send signal to process p1 to read first MAXR lines
    while(1); //run forever 
    return 0;
}

When above program is executed then process p2 doesn't read file at all ie file is completely read by p1 and p2 prints some garbage values.

What modification should be done in above code to work ? or What is the error is there ?

Finally it works Just i need to add fflush() after each in and out as.

cout<<buff;
fflush(stdout);
cin>>buff;
fflush(stdin);

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