fork 从哪里开始执行表单?
对于我之前关于分段错误的问题,我得到了非常有用的答案。感谢那些做出回应的人。
#include<stdio.h>
main()
{
printf("hello");
int pid = fork();
wait(NULL);
}
输出:你好你好。
在此,子进程从头开始执行。 如果我没有错,那么如果我将 sem_open 放在 fork() 之前,程序将如何工作 (参考对:上一个问题的回答)
我需要一个关于偶尔发生但并不总是发生的分段错误的清晰解释。为什么不总是...如果编码中有任何错误,那么它应该总是正确地发生...?
To my previous question about segmentation fault ,I got very useful answers.Thanks for those who have responded.
#include<stdio.h>
main()
{
printf("hello");
int pid = fork();
wait(NULL);
}
output: hellohello.
In this the child process starts executing form the beginning.
If Iam not wrong , then how the program works if I put the sem_open before fork()
(ref answers to :prev questions)
I need a clear explanation about segmentation fault which happens occasionally and not always. And why not always... If there is any error in coding then it should occur always right...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fork
创建进程的克隆。从概念上讲,父级的所有状态也最终会传递给子级。这包括:因此...您的程序不会从任何地方“开始运行”...调用
fork
时拥有的所有状态都将传播给子进程。子进程将从fork
返回,就像父进程一样。至于分叉后你可以做什么...我不确定 POSIX 说什么,但我不会依赖信号量在分叉后做正确的事情。您可能需要一个进程间信号量(请参阅
man sem_open
或sem_init
的pshared
参数)。根据我的经验,跨进程信号量在免费的 Unix 类型操作系统上并没有得到很好的支持...(例如:如果您尝试创建一个 BSD,某些 BSD 总是会失败,并出现ENOSYS
。)@GregS 提到了分叉后出现重复的“hello”字符串。他正确地说stdio(即
FILE*
)将在用户空间内存中缓冲,并且fork
导致字符串在两个进程中缓冲。您可能想调用 fflush(stdout); fflush(stderr); 并在fork
之前刷新任何其他重要的FILE*
句柄。fork
creates a clone of your process. Conceptually speaking, all state of the parent also ends up in the child. This includes:Therefore... Your program will not "start running" from anywhere... All the state that you had when you called
fork
will propagate to the child. The child will return fromfork
just as the parent will.As for what you can do after a fork... I'm not sure about what POSIX says, but I wouldn't rely on semaphores doing the right thing after a
fork
. You might need an inter-process semaphore (seeman sem_open
, or thepshared
parameter ofsem_init
). In my experience cross-process semaphores aren't really well supported on free Unix type OS's... (Example: Some BSDs always fail withENOSYS
if you ever try to create one.)@GregS mentions the duplicated "hello" strings after a fork. He is correct to say that stdio (i.e.
FILE*
) will buffer in user-space memory, and that afork
leads to the string being buffered in two processes. You might want to callfflush(stdout); fflush(stderr);
and flush any other importantFILE*
handles before afork
.不,它从
fork()
开始,在子进程中返回 0,或者在父进程中返回子进程 ID。您会看到“hello”两次,因为标准输出已被缓冲,并且实际上尚未在分叉点写入。然后父级和子级都实际写入缓冲的输出。如果在
printf()
之后使用fflush(stdout);
,您应该只会看到它一次。No, it starts from the
fork()
, which returns 0 in the child or the child's process ID in the parent.You see "hello" twice because the standard output is buffered, and has not actually been written at the point of the fork. Both parent and child then actually write the buffered output. If you
fflush(stdout);
after theprintf()
, you should see it only once.