c - 程序因调用 execvp 编译错误的程序而崩溃?

标签 c process c89 process-control

我使用 execvp 编译程序时出错。但随后我的终端屏幕上弹出错误消息,这不应该发生,因为如果 execvp 失败,它只会让子进程以退出状态返回。我不明白为什么我的终端实际上​​会显示错误消息?

我的命令数组:{gcc,studentcode.c,ourtest3.c,-o,ourtest3.x,NULL},在ourtest3.c中,我故意犯了几个错误。我的调用函数是这样的:

commands = {"gcc", "studentcode.c", "ourtest3.c", "-o", "ourtest3.x", NULL};
int compile_program(Char** commands) {
  pid_t pid;
  int status;

  pid = safe_fork();
    if (pid == 0) { /*Child*/
      if (execvp(commands[0], commands) < 0) {
    exit(0);
      }
    } else { /*Parent*/
      if (wait(&status) == -1) {
    return 0;
      }
      if (WIFEXITED(status)) {
    if (WEXITSTATUS(status) != 0) {
      return 1;
    }
      } else {
    return 0;
      }
    }
  return 1;
}

ourtest3.c是这样的:

#include <stdio.h>
#include <assert.h>
#include "studentcode.h"

int main(void) {
  assert(product(2, 16) == 32

  printf("The student code in public07.studentcode.c works on its ");
  printf("third test!\n");

  return 0;
}

我的程序应该正常结束并返回值 0,但相反,在我的终端窗口上,它显示

ourtest3.c: In function 'main':
ourtest3.c:19:0: error: unterminated argument list invoking macro "assert"
ourtest3.c:13:3: error: 'assert' undeclared (first use in this function)
ourtest3.c:13:3: note: each undeclared identifier is reported only once for each function it appears in
ourtest3.c:13:3: error: expected ';' at end of input
ourtest3.c:13:3: error: expected declaration or statement at end of input

最佳答案

如果您想更改进程的 stdin、stout 和 stderr,您需要这样做。否则,它只是从其父级继承它们。在 fork 之后和 execvp 之前,您可能想要 open /dev/nulldup 将其放到文件描述符 0 和 1 上。

这是一些没有错误检查的丑陋代码:

if (pid == 0) { /*Child*/

  /* Redirect stdin and stderr to /dev/null */
  int fd = open ("/dev/null", O_RDONLY);
  dup2(STDIN_FILENO, fd);
  dup2(STDERR_FILENO, fd);
  close(fd);

  if (execvp(commands[0], commands) < 0) {
_exit(0);
  }

如果您希望父级能够访问子级的输出,您还可以将它们重定向到文件或管道。

注意对_exit的调用。不要养成对失败的 child 调用 exit 的习惯。这在过去曾导致过具有严重安全隐患的错误。想象一下,如果您的进程在退出时要执行某些操作(例如将缓冲区刷新到终端或网络连接)。通过在子进程中调用 exit,您可以执行该操作两次。您可能认为您知道自己没有这样的东西,但您不可能知道这一点(一般来说),因为您不知道您的库内部可能在做什么。

关于c - 程序因调用 execvp 编译错误的程序而崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472444/

相关文章:

c - C 编程语言的运算符优先级表

c - fgets() 不忽略换行符

c - 程序fork 4个子进程,每个子进程都会做不同的操作

c - 在 ANSI C 中使用 WinAPI 和 DWMApi

c - 通过指针访问 C union 成员

c - 套接字操作上的非套接字错误

java - 关闭进程以运行时 exec() 开始;

从多进程 docker 容器记录

c - 矩阵未在声明中填零

c - 具有 C99 内联函数的 OpenBSD 5.9 header