gpt4 book ai didi

无法在 C 中使用 system() 函数执行 "cat"

转载 作者:行者123 更新时间:2023-12-02 16:10:54 27 4
gpt4 key购买 nike

我的 C 程序中有一个函数是 SIGINT 信号的处理程序,执行时应该简单地执行以下命令:

void sigint_handler(int sig)
{
system("cat output.txt");
exit(0);
}

问题是“cat”命令似乎没有做任何事情。如果我尝试做其他事情而不是“猫”,比如“echo ”,它工作正常,所以我相信问题出在“猫”而不是 system() 函数。文件“output.txt”位于 C 程序的同一目录中,如果我尝试通过另一个 C 脚本对该文件执行 cat,它会起作用。此外,如果我尝试从 shell 执行该命令,它也能正常工作。

我已经检查了 system("cat output.txt") 的返回值,它是 0。那么问题是什么?

编辑:文件 output.txt 也作为文件流(使用 fopen())在程序中由另一个线程打开,这可能是个问题吗?

最佳答案

您应该知道信号处理程序只能安全地调用一组受限制的 async-signal-safe functions . system()exit() 都不在列表中。调用它们可能会触发未定义的行为,从而导致不可预知的结果。

You say :

I see, but I don't understand why his version is working while mine is not. I declare the signal handler in the same way, but my program can't execute that "cat" command, while in his version it does.

我第二Charles Duffy's reply :

Sometimes things that aren't guaranteed still work despite not being guaranteed as an accident of environment or configuration. That doesn't make the code that just happens to work correct; good code relies only on documented, guaranteed semantics.

一个常见的解决方法是将信号处理代码移至主程序,并让主程序定期检查 global variable .从信号处理程序中,所有要做的就是设置全局变量并返回。这种技术可以让您随心所欲,尽管方式有些复杂。

volatile sig_atomic_t sigint_received = 0;

void sigint_handler(int sig)
{
sigint_received = 1;
}
// main program loop
for (;;) {
// do stuff
...

// check for interruption
if (sigint_received) {
system("cat output.txt");
​exit(0);
}
}

关于无法在 C 中使用 system() 函数执行 "cat",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68049208/

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