为什么超时不能在sudo下运行tcpdump生效?

时间:2017-02-01 07:50:51

标签: linux bash tcpdump

我想运行tcpdump命令,时间限制为10秒。

timeout 10 sudo tcpdump -i eth0 -nn 'host 192.168.1.176'

它不会停止。为什么timeout命令不会在tcpdump生效?

2 个答案:

答案 0 :(得分:3)

问题是timeout以您的用户权限运行。 sudo进程将权限升级为root(或其他用户),因此不允许timeout将SIGTERM发送到子进程。这可以通过strace显示(我以#开头的评论,以及可读性的空行):

user$ strace timeout 1 sudo sleep 5
# lots of irrelevant stuff
# here, timeout sets up the timer to get a signal when the child should be terminated
rt_sigprocmask(SIG_UNBLOCK, [ALRM], NULL, 8) = 0
timer_create(CLOCK_REALTIME, {sigev_value={sival_int=1889673072, sival_ptr=0x560c70a21f70}, sigev_signo=SIGALRM, sigev_notify=SIGEV_SIGNAL}, [0]) = 0
timer_settime(0, 0, {it_interval={tv_sec=0, tv_nsec=0}, it_value={tv_sec=1, tv_nsec=0}}, NULL) = 0
wait4(12320, 0x7ffdfeb0ef0c, 0, NULL)   = ? ERESTARTSYS (To be restarted if SA_RESTART is set)

# the signal arrives
--- SIGALRM {si_signo=SIGALRM, si_code=SI_TIMER, si_timerid=0, si_overrun=0, si_value={int=1889673072, ptr=0x560c70a21f70}} ---

# timeout tries to kill the child
kill(12320, SIGTERM)                    = -1 EPERM (Operation not permitted)
# and gets EPERM!

修复是使用root权限运行超时。以下内容将按预期工作:

user$ sudo timeout 1 sleep 5

当然,如果您已经 root,那么在timeout 1之前或之后是否在命令行中放置sudo并不重要。

root$ sudo timeout 1 sleep 5
root$ timeout 1 sudo sleep 5

答案 1 :(得分:1)

请改为尝试:

sudo timeout 10 tcpdump -i eth0 -nn 'host 192.168.1.176'