Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support daemon(fork twice) for Darwin/OSX #23

Closed
winlinvip opened this issue Oct 17, 2021 · 1 comment
Closed

Support daemon(fork twice) for Darwin/OSX #23

winlinvip opened this issue Oct 17, 2021 · 1 comment

Comments

@winlinvip
Copy link
Member

winlinvip commented Oct 17, 2021

SRS分支改进后,去掉了对多进程的检测,而OSX在fork后会关闭fd,导致kevent返回-1死循环。

在初始化时调用_st_kq_init创建了kqueue,fd是3:

(lldb) p _st_kq_data->kq
(int) $0 = 3

MB0:state-threads winlin$ lsof -p 31372|grep KQUEUE
srs     31372 winlin    3u  KQUEUE                                       count=0, state=0

运行后,daemon经过两次fork,fd=3已经关闭,变成了pid文件了:

MB0:state-threads winlin$ lsof -p 31695
COMMAND   PID  USER   FD   TYPE             DEVICE   SIZE/OFF                NODE NAME
srs     31695 winlin    3w   REG                1,4          5            31611904 /Users/winlin/git/srs/trunk/objs/srs.pid

最初是有pid改变的检测的( event.c#L970 ),由于在linux下没有用多进程,所以在这个分支去掉了这个逻辑。

@winlinvip
Copy link
Member Author

winlinvip commented Oct 17, 2021

应该是fork在不同平台的逻辑不相同。

看了下并不是FD_CLOEXEC造成的,去掉这两行也不行:

fcntl(_st_kq_data->kq, F_SETFD, FD_CLOEXEC);
fcntl(_st_epoll_data->epfd, F_SETFD, FD_CLOEXEC);

在Linux下,fork并不会关闭fd,只有在fork然后exec才会关闭:

CLOEXEC is short for "close on exec". It means the descriptor will be closed automatically when the process calls exec(). It's not closed when forking. LINK

当fork子进程后,仍然可以使用fd。但执行exec后系统就会字段关闭子进程中的fd了,如果不设置该close_on_exec标志位,子进程的fd将复制到exec之后的进程中。链接

在Linux下验证没有问题,第一次fork:

[New inferior 2 (process 28579)]
[Detaching after fork from parent process 28534]

第一次fork后,fd还在:

[root@8b38255ddb3b srs]# lsof -p 28534 |grep poll
srs     28534 root    7u  a_inode               0,12        0    12326 [eventpoll]
[root@8b38255ddb3b srs]# lsof -p 28579 |grep poll
srs     28579 root    7u  a_inode               0,12        0    12326 [eventpoll]

daemon是两次fork,看后面再fork孙子进程:

[New inferior 3 (process 28604)]
[Detaching after fork from parent process 28579]

发现fd=7还在,并没有关闭:

[root@8b38255ddb3b srs]# lsof -p 28604 |grep poll
srs     28604 root    7u  a_inode               0,12        0    12326 [eventpoll]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant