What is causing my program to hang and not exit properly? (pipe, read system call, while loop)

ぃ、小莉子 提交于 2021-01-27 11:22:48

问题


I have a program where I write from several child processes to a pipe, and then attempt to read all the messages written to each process, from each pipe, and print them to the screen. With the following code (specifically, the while loop using the read system call to store the messages into buffer buf), my program will hang and not exit, nor print all of the messages sent to the 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 does not print all the messages (as they aren't all read):

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

This is my code writing to the pipes:

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"

which 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
}

回答1:


Maybe b/c you didn't close the pipe? if write end is not closed, read will keep on hanging

Trying adding

close(pfds[j][1]);

after you write your msgs to the pipe




回答2:


read(fd) (where fd is the read end of a pipe) will only return 0 when all write ends for the pipe have been closed.

Note that fork()-ing will duplicate all open file descriptors. So this:

int fd[2];
pipe(fd);
if (fork() == 0) {
  write(fd[1], "abc", 3);
  close(fd[1]);
} else {
  char buf[100];
  while (read(fd[0], buf, 100) > 0) {
    // ...
  }
}

will cause an infinite loop (because fd[1] is still open in the parent process), while this:

int fd[2];
pipe(fd);
if (fork() == 0) {
  write(fd[1], "abc", 3);
  close(fd[1]);
} else {
  close(fd[1]);

  char buf[100];
  while (read(fd[0], buf, 100) > 0) {
    // ...
  }
}

should terminate.



来源:https://stackoverflow.com/questions/20082434/what-is-causing-my-program-to-hang-and-not-exit-properly-pipe-read-system-cal

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