gpt4 book ai didi

c - fork 后在子进程中设置 errno - OSX

转载 作者:太空狗 更新时间:2023-10-29 16:07:41 25 4
gpt4 key购买 nike

这是我今天在 Mac OSX 上发现的一件奇怪的事情。

fork成功后,errno设置为0在父亲的进程中(如预期的那样),但在子进程中设置为 22。这是源代码:

#include <stdio.h> 
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main(int nbArgs, char** args){
int pid;
errno = 0;
printf("Errno value before the call to fork : %d.\n", errno);
if ((pid = fork()) == -1){
perror("Fork failed.");
exit(1);
}
if (pid == 0){
printf("Child : errno value : %d.\n", errno);
}else{
printf("Father : pid value : %d ; errno value : %d.\n", pid, errno);
wait(NULL);
}
exit(0);
}

执行轨迹:

Remis-Mac:TP3 venant$ ./errno_try
Errno value before the call to fork : 0.
Father : pid value : 9526 ; errno value : 0.
Child : errno value : 22.

据我所知,根据Opengroup specifications ,“新进程(子进程)应该是调用进程(父进程)的精确副本,除非下面详述 [...]”,包括全局变量 errno 的值 -_-

有没有人知道解释这种不良行为的线索?

最佳答案

很好奇...我可以使用 GCC 4.8.2 和 Clang 在 Mac OS X 10.9 Mavericks 上重现该问题。

POSIX 表示一些失败的函数将设置 errno ( fork() 是其中一个函数),但并没有说成功的函数不会设置 errno .例如,在 Solaris 上,许多标准 I/O 函数设置 errno如果输出流不是终端。但是,重置 errno = 0;printf()之后不会改变 Mac OS X 上的行为。

POSIX 2008(系统接口(interface) - 一般信息:3. Error numbers):

Some functions provide the error number in a variable accessed through the symbol errno, defined by including the <errno.h> header. The value of errno should only be examined when it is indicated to be valid by a function's return value. No function in this volume of POSIX.1-2008 shall set errno to zero. For each thread of a process, the value of errno shall not be affected by function calls or assignments to errno by other threads.

如果fork()失败,然后 errno将被设置为指示失败。当它成功时,检查 errno 在技术上是无效的.这就是为什么的证明。

关于c - fork 后在子进程中设置 errno - OSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com