Why is output of parent process blocked by child process?

有些话、适合烂在心里 提交于 2019-12-06 10:04:11

The parent process is reading the child's message via fgets(). It will continue to read until one of three things happens:

  • enough bytes have been read to fill the buffer, less one for a string terminator
  • a newline is read
  • end-of-file is encountered

The child does not send enough bytes to exhaust the buffer, and it does not send a newline, so the parent's fgets() does not return until the child's end of the pipe is closed upon its exit.

You can fix this in the child by having it either terminate the message with a newline or close the stream immediately after writing.

If you close the file in the client right after flushing, it will work as expected:

fflush(fpc);
fclose(fpc);

Output:

[dbush] /tmp/x1 hello
hello
[dbush] This is the child process. Closing

Your problem is the fgets call. It tries to fulfill your request fully, and that's the cause of the blocking.

If you're prototyping some IPC, I recommend you ditch stdio and go for the raw IO syscalls.

If you substitute, e.g.:

char buf[100];
read(pipefd[0], buf, 100);
fprintf(stdout,"%s\n",buf);

for the fgets part, you'll get your message right away, because read will give you whatever's available and return (if there's at least 1 byte in the pipe buffer at the time you make the read request), whereas fgets won't back off until it has read all the requested bytes or until it figures out it can't (EOF or an IO error).

(To split hairs, it's not fgets that's blocking (userspace code alone can't block) -- it's another momentarily unsatisfiable read syscall that fgets has issued).

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