What caused my program to hang without quitting normally? (pipeline, read system call, while loop)

I have a program. I write to the pipeline from several sub processes, and then try to read all messages written to each process from each pipeline and print them to the screen Using the following code (specifically, a while loop that uses the read system call to store messages in the buffer buf), my program will hang without exiting and will not print all messages sent to different processes

for (i = 0; i < MAXP; i++) {
    if(id == i) {
        while(read(pfds[i][0],buf,sizeof(buf)) > 0)
             printf("process%d has received a message from %s\n",i,buf);    
    }
}

However, with the following code, the program exits correctly, but not all messages are printed (because they are not all read):

for (i = 0; i < MAXP; i++) {
    if(id == i) {
        nbytes = read(pfds[i][0],sizeof(buf));
        printf("process%d has received a message from %s\n",buf); 
    }
}

This is the code I write to the pipeline:

write(pfds[j][1],msg,9);  // write the message to j pipe

And the message is:

sprintf(msg,"process%d",i); // create the message - 9 bytes (inc. null term)
// the message is "process0" or "process1" ... through "process8"

This is a 9-byte char array:

char msg[9];

solution

for (j = 0; j < MAXP; j++) {
    close(pfds[j][1]); // close write to j from i
}

Solution

Maybe B / C you didn't close the pipe? If the write end is not closed, the read continues to be suspended

Try adding

close(pfds[j][1]);

After writing msgs to the pipe

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>