Why does process child execute some unexpected line?

耗尽温柔 提交于 2019-12-02 01:41:10

child is getting back into the main instead of getting terminated by the exit..no, that's not the case.

There are many issues with your code.

  1. \Child will give you error in terms of "unknown escape sequence", change to \nChild.
  2. include stdlib.h for exit().
  3. include unistd.h for fork()
  4. add \n to printf("Heeeyoooo!"); to flush the output buffer.

After 1,2 and 3, the main problem in your code is, there is no newline escape sequence present in your printf() which is why your output buffer is not flushed. So, to flush out the standard output buffer before next print, add a newline escape sequence [\n] which will flush the buffer.

Worth of mentioning, from the man page of fork()

The child process shall have its own copy of the parent's open directory streams. Each open directory stream in the child process may share directory stream positioning with the corresponding directory stream of the parent

which means, without the flushing of the buffer, Heeeyoooo! is still present in child's output stream and hence it is printed again.

If you write

printf("Heeeyoooo!");
fflush(stdout);

and then fork, the error goes away. The reason is that fork() clones the output buffer for stdout while "Heeeyoooo!" is still in it, so it is subsequently printed twice.

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