一个nohup导致程序崩溃的Bug

36 篇文章 1 订阅

程序使用nohup启动崩溃,不使用nohup启动正常。

先说原因:socket connect失败返回文件描述符0; 文件描述符 fd=0 表示标准输入stdin; nohup把标准输入重定向到 /dev/null; epoll_ctl()或其他方式使用该文件描述符时报错。

1. 文件描述符

一个文件描述符就是一个唯一的标志,可以标定一个标准输入/输出, 可以标定一个文件, 也可以标定一个socket.

A file descriptor is a number that uniquely identifies an open file in a computer’s operating system. It describes a data resource, like a network socket. a unique non-negative integer
The descriptor is identified by a unique non-negative integer, such as 0, 1, 2, …

特别地,0,1,2 分别代表 stdin, stdout, stderr, 即标准输入,标准输出,标准错误
我们常见到命令后面加上
*** > foo.log 2>&1
意思是把标准错误重定向到标准输出, 标准输出重定向到文件foo.log

2. socket()

socket()返回一个a file descriptor, 回取当前系统最小的可用文件描述符,比如3。 如果我们使用
close(0);
关闭stdin之后,socket()就会返回0。 
当然本案不使用socket().

3. nohup

nohup把屏蔽发给进程的SIGHUP信号, 一般和命令末尾的配合使用。

If standard input is a terminal, redirect it from /dev/null. If standard output is a terminal, append output to ‘nohup.out’ if possible, ‘$HOME/nohup.out’ otherwise. If standard error is a terminal, redirect it to standard output. To save output to FILE, use ‘nohup COMMAND > FILE’.

并且会把stdin重定向到/dev/null空设备, 把标准输出重定向到nohup.out或者指定文件。

4. 对于未指定任何目标的文件描述符操作可能导致程序崩溃

举例:

#include <sys/epoll.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <string.h>

int main()
{
    //close(0);
    
    int epollfd = epoll_create1( EPOLL_CLOEXEC );
    if( epollfd == -1 )
    {
        std::cerr << "epoll_create failed: " << epollfd << "errno: " << errno << " " << strerror(errno) << std::endl;
    }
    struct epoll_event ev;
    ev.events = EPOLLIN;

    ev.data.fd = 0;
    if( epoll_ctl( epollfd, EPOLL_CTL_ADD, ev.data.fd, &ev )  )
    {
        std::cerr << "epoll_ctl add td server fd failed" << "errno: " << errno << " " << strerror(errno) << std::endl;
    }
    return 0;
}

执行报错:
errno: 22 Invalid argument

如果把close(0)注释掉,则能通过。
但是这时用nohup起仍会报错(原因见以上分析):
errno: 1 Operation not permitted

如果设置 ev.data.fd = 12345; 一个没有指定目标的文件描述符,执行会报错:
errno: 9 Bad file descriptor


Ref:
https://www.computerhope.com/jargon/f/file-descriptor.htm
https://m.jb51.net/article/172361.htm
https://linux.die.net/man/1/nohup

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值