在 linux gcc 中使用 fork() [英] Working of fork() in linux gcc

查看:26
本文介绍了在 linux gcc 中使用 fork()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fork() 创建一个新进程,子进程从父进程的当前状态开始执行.

fork() creates a new process and the child process starts to execute from the current state of the parent process.

这就是我对 Linux 中 fork() 的了解.

This is the thing I know about fork() in Linux.

因此,相应的代码如下:

So, accordingly the following code:

int main() {
  printf("Hi");
  fork();
  return 0;
}

如上所述,只需要打印一次Hi".

needs to print "Hi" only once as per the above.

但是在用 gcc 编译的 Linux 中执行上述内容时,它会打印Hi"两次.

But on executing the above in Linux, compiled with gcc, it prints "Hi" twice.

有人可以向我解释使用 fork() 实际发生了什么,以及我是否正确理解了 fork() 的工作原理?

Can someone explain to me what is happening actually on using fork() and if I have understood the working of fork() properly?

推荐答案

(结合用户@Jack 的评论中的一些解释)当您将某些内容打印到标准输出"标准输出(通常是计算机显示器,尽管您可以将其重定向到文件)时,它最初会存储在临时缓冲区中.

(Incorporating some explanation from a comment by user @Jack) When you print something to the "Standard Output" stdout (computer monitor usually, although you can redirect it to a file), it gets stored in temporary buffer initially.

fork 的两侧都继承了未刷新的缓冲区,因此当 fork 的每一侧都遇到 return 语句并结束时,它会被刷新两次.

Both sides of the fork inherit the unflushed buffer, so when each side of the fork hits the return statement and ends, it gets flushed twice.

在你 fork 之前,你应该 fflush(stdout); 这将刷新缓冲区,以便孩子不会继承它.

Before you fork, you should fflush(stdout); which will flush the buffer so that the child doesn't inherit it.

stdout 到屏幕(而不是将它重定向到文件时)实际上是由行尾缓冲的,所以如果你完成了 printf("Hi ");你不会有这个问题,因为它会刷新缓冲区本身.

stdout to the screen (as opposed to when you're redirecting it to a file) is actually buffered by line ends, so if you'd done printf("Hi "); you wouldn't have had this problem because it would have flushed the buffer itself.

这篇关于在 linux gcc 中使用 fork()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆