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

标签 c bash posix system cat

我的 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/

相关文章:

c - 埃尔卡皮坦 : Undefined symbol "start" whenever I compile a C program

c - 使用 fread() 读取结构体

bash - 从另一个脚本获取 shell 脚本并检查返回码

linux - ssh 命令输出以保存在 shell 脚本中的文本文件中

c - 关于用多线程实现 sleep 理发师时的同步

linux - SIGKILL 权限策略是什么?

c - 使用fgetc读取单词?

ruby - 从流中删除文件中的行

linux - 条件变量和rwlock死锁

c - 在 C 中解析 Twitter 提要