简体   繁体   English

在Linux中使用两个进程读取文件?

[英]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 . 进程p1将打开一个文件,然后p1将在一定数量的行之前读取该文件,进程p2将在p1将被读取之后在那里读取同一文件,依此类推,直到文件结束。 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 . 例如,文件包含100行,则p1将读取0-10行,然后p2将读取10-20行,然后p1将读取20-30行,依此类推。

code of p1 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 // 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. 执行上述程序后, process p2 doesn't read file at all即p1完全读取了文件,而p2打印了一些垃圾值。

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. 终于可以正常工作了,只是我需要在每次进出后都添加fflush()。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM