执行一个正在运行的进程

时间:2018-06-04 18:00:58

标签: linux bash

我目前有一个Bash脚本,最后使用exec来启动正在运行的服务器进程:

#! /bin/bash
.
.
.
exec python -m SimpleHTTPServer 8080

但是现在,我不想仅仅exec执行命令,而是在exec压缩我的调用shell程序之前“热身”服务器进程。有点像:

#! /bin/bash

python -m SimpleHTTPServer 8080 &

for index in $(seq 100); do
    curl -X GET http://localhost:8080/warm/up
done

# => How can I exec when my command is already running?

据我了解,exec只能接受命令,但不能接受正在运行的进程PID等。

在这种情况下,我真的不想将调用的Bash shell留作python服务器的父节点,以避免在父节点中出现任何信号处理陷阱。

3 个答案:

答案 0 :(得分:1)

只需预测您的热身而不是服务器:

#! /bin/bash

{
  sleep 5
  for index in $(seq 100); do
    curl -X GET http://localhost:8080/warm/up
  done
} &

exec python -m SimpleHTTPServer 8080

答案 1 :(得分:0)

执行此操作以启动服务器并将其与shell进程取消关联

nohup python -m SimpleHTTPServer 8080 &
disown

然后你可以调用你的热身网址并简单地让脚本退出。

答案 2 :(得分:0)

何时使用exec command

来自man bash(尝试man -P'less +"/^ *exec "' bash):

   exec [-cl] [-a name] [command [arguments]]
          If command is specified, it replaces the shell.  No new  process
          is  created.  The arguments become the arguments to command...

所以That other guy's answer是正确的,但你使用的方式也是正确的! The point of glenn jackman非常重要,以防您计划使用此脚本在生产环境中运行服务器(即:关闭会话后让它们保持运行)。

exec command [args] 的目标是结束当前的shell会话并改为运行 command [and args] 。作为替换但使用相同的进程ID 。当您在文件中记录进程ID 时,这非常有用:

#!/bin/bash

echo $$ >/var/run/SimpleHTTPServer.pid
exec python -m SimpleHTTPServer 8080

#!/bin/bash

bash -c 'echo $$ >/var/run/SimpleHTTPServer.pid &&
       exec python -m SimpleHTTPServer 8080' &

for index in $(seq 100); do
    curl -X GET http://localhost:8080/warm/up
done
相关问题