c - 如果我的系统调用引发错误,是否可以容忍?

标签 c linux unix operating-system

我正在实现多级管道流程。为了避免竞争条件,我必须在父进程和子进程中为子进程设置进程组。但是,如果子进程已进入 execvp,则父进程中的 setpgid 可能会引发错误。

  • 是否有任何经验法则表明我们应该在任何系统调用引发错误时退出程序?
  • 我可以捕捉到这样的错误并继续我的程序吗?
  • 这是一个好的编码约定吗?
  • 有没有更优雅的方法来处理这种情况?

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

#define CHECK(syscall, msg) do {                    \
    if ((syscall) == -1) {                          \
      perror(msg);                                  \
      _exit(1);                                     \
    }                                               \
  } while(0)

int main () {
  int ls_pid;
  char *ls_argv[] = { "ls", NULL };

  CHECK(ls_pid = fork(), "fork error");
  if (!ls_pid) {
    CHECK(setpgid(0, 0), "setpgid error");
    CHECK(tcsetpgrp(STDIN_FILENO, 0), "tcsetpgrp error");
    CHECK(execvp(ls_argv[0], ls_argv), "execvp error");
  } else {
    // sleep(2);
    setpgid(ls_pid, ls_pid); // This might give error if the child process has entered execvp. 
    // It returns -1 if uncommenting the sleep(2) above.
  }

  CHECK(wait(NULL), "wait error");
  printf("Finish\n");
}

最佳答案

我想下面的链接可以很好地回答您的问题:

POSIX, Part 1: Error handling

但我认为您没有使用良好的编码约定。它对错误的容忍度很低。

关于c - 如果我的系统调用引发错误,是否可以容忍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48602730/

相关文章:

c - 二维阵列打印

android - 从命令行删除持久僵尸进程

linux - grep + 如果找不到相关匹配,一段时间后添加超时

linux - 无法删除名为 ";"的未知文件

c - 发生溢出,但 errno 不是 ERANGE。这是怎么发生的?

c - 使用 flex-lexer 和 cmake 构建错误

multithreading - 是否可以切换应用程序线程的用户和组?

linux - 使用 awk 和行首正则表达式获取段落

c - 将 'const int' 分配给 'int' 时没有警告

linux - 从 lsof(Linux 命令行)中提取字段/属性