程序使用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