linux script with netcat stops working after x hours

后端 未结 6 1910
闹比i
闹比i 2021-02-20 11:20

I\'ve have to scripts:

#!/bin/bash

netcat -lk -p 12345 | while read line
do
    match=$(echo $line | grep -c \'Keep-Alive\')
    if [ $match -eq 1 ]; then
              


        
6条回答
  •  星月不相逢
    2021-02-20 12:07

    If none of your commands including netcat reads input from stdin you can completely make it run independent of the terminal. Sometimes background process that are still dependent on the terminal pauses (S) when they try to read input from it on a background. Actually since you're running a daemon, you should make sure that none of your commands reads input from it (terminal).

    #!/bin/bash
    
    set +o monitor # Make sure job control is disabled.
    
    (
        : # Make sure the shell runs a subshell.
        exec netcat -lk -p 12345 | while read line  ## Use exec to overwrite the subshell.
        do
            match=$(echo $line | grep -c 'Keep-Alive')
            if [ $match -eq 1 ]; then
                [start a command]
            fi
        done
    ) <&- >&- 2>&- /dev/null &
    
    TASKPID=$!
    sleep 1s ## Let the task initialize a bit before we disown it.
    disown "$TASKPID"
    

    And I think we could try the logging thing again:

    set +o monitor
    
    (
        echo "[$(date "+%F %T")] Starting loop with PID $BASHPID."
    
        for (( ;; ))
        do
            echo "[$(date "+%F %T")] Starting netcat."
    
            netcat -vv -lk -p 12345 | while read line
            do
                match=$(echo "$line" | grep -c 'Keep-Alive')
                if [ "$match" -eq 1 ]; then
                    [start a command]
                fi
            done
    
            echo "[$(date "+%F %T")] Netcat has stopped or crashed."
    
            sleep 4s
        done
    ) <&- >&- 2>&- > "/var/log/something.log" 2>&1 &
    
    TASKPID=$!
    sleep 1s
    disown "$TASKPID"
    

提交回复
热议问题