`wait()` 和 `exit()` 这两种用法哪个更好?
Which of these two usages of `wait()` and `exit()` is better?
中了解到的wait()
和exit()
的一些用法
f(){
child_pid = fork();
if (child_pid) {
// parent part
...
while (wait(NULL) == -1 && errno == EINTR) ;
...
exit();
}
// common part, which is actually child part
...
}
f();
// common part 2, which is actually child part
...
和这个一样吗?
f(){
child_pid = fork();
if (child_pid) {
// parent part
...
while (wait(NULL) == -1 && errno == EINTR) ;
...
exit();
}
if (child_pid == 0) {
// common part, which is actually child part
...
// common part 2, which is actually child part
...
}
}
f();
第二个比第一个更容易理解吗? That is what I feel (especially the above code is wrapped in a function, and a call to that function has other common code following it in main()
),但我真的不是很了解
有没有第一个比第二个更好的原因或案例?
特别是login
(上面第一个link)的实现为什么选择第一种方式?
这实际上是一个函数内部属于什么的问题,有点模糊。但是,如果您的函数类似于 "put me into a new process that has its environment set up in some particular way",那么该代码具有如下结构是有意义的:
void switch_to_child(){
int pid = fork();
if (pid < 0){
exit_with_an_error();
}
if (pid > 0){
wait_and_exit_in_parent();
}
set_up_child_environment();
}
initialize_stuff();
switch_to_child();
do_child_stuff();
另一方面,如果您的函数类似于 "spawn a new process to do something",则代码具有如下结构更有意义:
void make_child(){
int pid = fork();
if (pid < 0){
exit_with_an_error();
}
if (pid == 0){
do_child_stuff();
exit_in_child();
}
}
initialize_stuff();
make_child();
wait_and_exit_in_parent();
wait()
和exit()
的一些用法
f(){
child_pid = fork();
if (child_pid) {
// parent part
...
while (wait(NULL) == -1 && errno == EINTR) ;
...
exit();
}
// common part, which is actually child part
...
}
f();
// common part 2, which is actually child part
...
和这个一样吗?
f(){
child_pid = fork();
if (child_pid) {
// parent part
...
while (wait(NULL) == -1 && errno == EINTR) ;
...
exit();
}
if (child_pid == 0) {
// common part, which is actually child part
...
// common part 2, which is actually child part
...
}
}
f();
第二个比第一个更容易理解吗? That is what I feel (especially the above code is wrapped in a function, and a call to that function has other common code following it in main()
),但我真的不是很了解
有没有第一个比第二个更好的原因或案例?
特别是login
(上面第一个link)的实现为什么选择第一种方式?
这实际上是一个函数内部属于什么的问题,有点模糊。但是,如果您的函数类似于 "put me into a new process that has its environment set up in some particular way",那么该代码具有如下结构是有意义的:
void switch_to_child(){
int pid = fork();
if (pid < 0){
exit_with_an_error();
}
if (pid > 0){
wait_and_exit_in_parent();
}
set_up_child_environment();
}
initialize_stuff();
switch_to_child();
do_child_stuff();
另一方面,如果您的函数类似于 "spawn a new process to do something",则代码具有如下结构更有意义:
void make_child(){
int pid = fork();
if (pid < 0){
exit_with_an_error();
}
if (pid == 0){
do_child_stuff();
exit_in_child();
}
}
initialize_stuff();
make_child();
wait_and_exit_in_parent();