叉在linux GCC工作() [英] Working of fork() in linux gcc

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

问题描述

叉()创建一个新的进程和子进程开始从父进程的当前状态执行。

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

这是我知道的的东西叉()在Linux中。

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

因此​​,相应地,下面code:

So, accordingly the following code:

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

需要打印嗨只有一次按照上面。

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

但在Linux中执行上面,用gcc遵守,它打印你好的两次

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

有人能向我解释什么是使用叉()实际发生的事情,如果我已经明白的工作叉()是否正确?

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.

叉的两侧继承未刷新缓冲器,所以,当车叉的每一侧击中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.

您叉之前,您应该 fflush(标准输出); 这将刷新缓冲区使孩子不继承它

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

标准输出到屏幕上(而不是当你重定向到一个文件),实际上是通过行缓冲结束,因此,如果你做了的printf(你好\\ n); ,你不会有这个问题,因为它会刷新缓冲区本身。

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\n"); you wouldn't have had this problem because it would have flushed the buffer itself.

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

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