Search code examples
linuxbashshellawkpid

Get PID in bash file with open screen


I am a beginner in bash programming. I want to obtain PIDs from processes, in order to use trap and kill to receive and send signals to a program in the same file.

In particular, I start the program opening a screen in this way:

screen -d -m  "start program"
process_id=`/bin/ps -fu $USER| grep "program" | grep -v "grep" | awk '{print $2}'`

The variable process_id contains two PIDs, not one. If I run without a screen, I don't have this issue (anyway, I have to open the screen).

Does anyone have solutions to this problem?


Another question: If I write

screen -d -m  "start program">log

the log file isn't printed. Any suggestions?


Solution

  • For your first question, pgrep(or process grep) is what you are looking for.

    For instance, the following will return a list of PIDs of all bash processes running.

    preg bash
    

    And if you read the docs:

    -signal
    Defines the signal to send to each matched process. Either the numeric or the symbolic signal name can be used.


    Second question, you could either use the -LogFile flag if your version of screen supports it. Or specify the log file in your .screenrc configuration file.

    This has already been answered.


    Edit:

    If you can't access the user's home directory where the configuration file .screenrc is usually put, you could change the $SCREENRC environment variable to explicitly set to an alternative path for it.