wi_python 2017-04-28 18:08 采纳率: 0%
浏览 689

c++ fork daemon 退出了?

void daemonize(const char *cmd) {
int fd0, fd1, fd2;
  int i;
  pid_t pid;
  struct rlimit rl;
  struct sigaction sa;
  // clear file createtion mask.
  umask(0);
  // get maximum number of file description.
  if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
    printf("Can not get file limit.\n");
    exit(0);
  }
  // become a session leader to lose controlling TTY
  if ((pid = fork()) < 0) {
    printf("Can not fork.\n");
    exit(0);
  }
  else if (pid != 0)    //parent
    exit(0);
  setsid();
  // ensure future opens won't allocate controlling TTYs.
  sa.sa_handler = SIG_IGN;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction(SIGHUP, &sa, NULL) < 0) {
    printf("can not ignore SIGUP\n");
    exit(0);
  }
  if((pid = fork()) < 0) {
    printf("Can not fork.\n");
    exit(0);
  }
  else if(pid != 0)    //parent
    exit(0);
  if (chdir("/") < 0) {
    printf("can not change directory to /.\n");
    exit(0);
  }

  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;
  for (i = 0; i< rl.rlim_max; i++)
    close(i); #  i = 1为什么就退出了?

}

close(1)就退出了?
为什么啊?

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 19:41
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在C++中,close(1) 这个函数用于关闭标准输入文件描述符(stdin)。这个函数会返回一个 bool 类型的值。如果成功关闭,则返回 true;否则,返回 false

    当您调用 close(1) 时,操作系统将尝试关闭标准输入流。由于您在 C++ 中处理的是 POSIX 标准库,所以这通常不会导致程序崩溃或退出。但是,如果您在执行其他操作时也使用了标准输入流(例如通过 cinstd::getline),则可能会引发异常或错误。

    解决此问题的方法是确保您在调用 close(1) 后没有继续使用标准输入流。例如:

    #include <iostream>
    #include <string>
    
    int main() {
        std::cout << "Hello, World!" << std::endl;
    
        // 关闭标准输入流
        if (std::cin.fail())
            throw std::invalid_argument("Invalid input");
    
        return 0;
    }
    

    在这个例子中,我们首先打印了一个字符串来演示如何使用标准输入流。然后,我们检查标准输入是否失败,如果是,则抛出一个异常。这样可以确保无论我们在调用 close(1) 之前还是之后都正确地处理了标准输入流。

    评论

报告相同问题?