fork() 作为参数
通常当我需要在 C 中 fork 时,我会做这样的事情:
pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
我突然想到我可以放弃额外的变量并使用:
if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
除了不正确的错误处理之外,(为什么)这有效/无效?
Usually when I need to fork in C, I do something like this:
pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
It occured to me that I could ditch the extra variable and use:
if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
Improper error handling aside, (why) does this work/not work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你所建议的肯定会起作用。 然而,在任何行为良好的应用程序中,错误处理都不是可选的。 以下实现模式同样简洁,并且还可以处理错误。 此外,它将 fork() 返回值保存在 pid 变量中,以防您稍后想在父级中使用它来等待子级。
What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child.
您会丢失父进程中的子进程 ID,该 ID 会返回给父进程。 我认为你可以恢复该信息,但也许不是唯一的(也就是说,我认为你可以获得所有孩子的 PID,但不一定是你刚刚分叉的孩子的 PID)。 如果不需要知道孩子的PID,我觉得第二种方式就可以了。
另外,如果分叉出现错误,则返回 -1,而您在这两种情况下都没有测试该错误,这通常是一个错误。
You lose the child process ID in the parent, which is what is returned to the parent. I think you could recover that information, but perhaps not uniquely (that is, I think you could get the PID of all of your children, but not necessarily the PID of the child you just forked). If you don't need to know the child's PID, I think the second way is fine.
Also, -1 is returned if there's an error in forking, which you aren't testing for in either case, which is usually a mistake.
你应该这样做。 我从来不知道它不起作用。 史蒂文斯的书中就是这样做的。
You should do this instead. I've never known it to not work. It's how it's done in the Stevens books.
您可以在 C 中自由地执行此操作,并且它会起作用,因为父级和子级将从 fork 接收不同的返回值 - 并且首先对其进行评估。 唯一的问题是您提到的错误处理。 另外,如果您想对其进行操作,则没有任何其他方法可以恢复子 PID,例如使用 waitpid 等。
You are free to do that in C and it will work because the parent and child will receive different return values from the fork - and it is evaluated first. The only issues are the error handling as you mentioned. Also, you won't have any other way to recover the child PID in case you wanted to operate on it, such as with a waitpid, etc.