不带参数调用 exit()

标签 c linux

在“UNIX 环境中的高级编程”第 199 页(第 7.3 节)中,我读到:

If (a) any of these functions [exit, _exit, _Exit] is called without an exit status

我编写了一个简单的程序来验证这一点:

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

int main() {
    exit();
}

但是gcc source.c提示:

source.c:5:5: error: too few arguments to function ‘exit’

这怎么可能?他们的意思是“直接从程序集调用”吗?

编辑:该段落说:

All three exit functions expect a single integer argument, which we call the exit status. Most UNIX System shells provide a way to examine the exit status of a process. If (a) any of these functions is called without an exit status, (b) main does a return without a return value, or (c) the main function is not declared to return an integer, the exit status of the process is undefined.

最佳答案

如果您忘记了原型(prototype)(ANSI C 发明)并简单地将 exit 声明为采用 K&R 风格中未指定数量的参数

void exit();/*unspecified number of parameters*/

那么你可以这样做

void exit();/*unspecified number of parameters*/
int main()
{
    exit(1);
}

这是一个格式良好的程序。

使用这种类型的声明,编译器不会阻止您完全省略参数:

void exit();
int main()
{
    exit();
}

但这在技术上是未定义的 C。

实际上,exit位于一个单独的翻译单元(标准库)中,因此编译器无法将其搞乱,并且上述内容是否会崩溃或返回一些垃圾值取决于什么如果代码尝试读取具有未指定内容的寄存器或内存位置,您的机器会执行此操作。 (exit 将尝试抓取的未指定内容可能是“陷阱表示”,然后你会崩溃,否则它只会抓取并使用一些垃圾整数值。)

关于不带参数调用 exit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544149/

相关文章:

c - 算法-使用外部编解码器/调制解调器处理抖动和漂移

c - 在 WinAPI 中优雅地关闭无窗口应用程序

c - 逗号在这里具有什么功能,为什么不引起编译时错误?

ruby-on-rails - Linux 托管的 Web 语言/框架最像 asp.net mvc 5+

python - 你如何在 python 中找到带引号的数字列表的平均值?

c - 堆栈在 Linux 中以错误的方向增长

c - 这给我打字问题。如何将 001 存储在 arg 中

c - 在 RPCGen 中将字符指针从客户端传递到服务器

regex - 在文本文件中按列对唯一元素进行排序

linux - 使用 Diff 检查文件夹结构中更改的文件,忽略以模式开头的行