PI_newbee
Posts: 172
Joined: Mon Aug 26, 2013 7:41 pm

Sending CRTL+C to close shell script

Thu Aug 18, 2016 9:26 am

Hi.

How can i send CRTL+C command to terminate one external script ?

This is what am doing:
- waiting for button press
- if detected, run external shell script
- wait 20 seconds
- send termination signal and close shell script

Whole code is written in python and shell script is called as subprocess ( looking for better solution ).
Any idea how to send this crtl+c command ?

PIN

User avatar
Paeryn
Posts: 2986
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Sending CRTL+C to close shell script

Thu Aug 18, 2016 1:05 pm

CTRL-C usually sends the SIGINT signal to a process so you just need to do that.

Since you say your program is Python this is how to do it from Python :-

Code: Select all

import subprocess, signal, time

print("Starting...")
proc = subprocess.Popen("./wait") ## Run program
print("Waiting...")
time.sleep(2) ## Wait a bit
print("Sending CTRL-C...")
proc.send_signal(signal.SIGINT) ## Send interrupt signal
## You can also use one of these two
#proc.terminate() ## send terminate signal
#proc.kill() ## send kill signal (forcibly kill the process, it cannot be trapped so the process can't exit gracefully, use with caution)
She who travels light — forgot something.

PI_newbee
Posts: 172
Joined: Mon Aug 26, 2013 7:41 pm

Re: Sending CRTL+C to close shell script

Fri Aug 19, 2016 10:24 am

This is some test program that should start the script on button press and close it after 10 seconds:

Code: Select all

import RPi.GPIO as GPIO
import time
import os
import signal
import subprocess

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    input_state = GPIO.input(18)
    if input_state == False:
        print('Start AV streaming')
        os.system("/home/pi/test/script.sh")
        time.sleep(0.2)
...
def countdown(count):
    while (count >= 0):
        print ('The count is: ', count)
        count -= 1
        time.sleep(1)

countdown(10)
print ("Insert CTRL+C")
proc.send_signal(signal.SIGINT)
print ("Program terminated")
Is this what you are suggesting ?

PIN

User avatar
Paeryn
Posts: 2986
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Sending CRTL+C to close shell script

Fri Aug 19, 2016 10:45 am

No, use proc = subprocess.Popen() to start the script. os.system() doesn't give you easy access to the process id needed to send it the signal whereas Popen() does. The return value from Popen() is needed so you can call the send_signal() function of it.

If you need to pass arguments to the script then rather than passing a string pass a list of strings otherwise it won't work.

Code: Select all

proc = subprocess.Popen(['/home/pi/test/script.sh', 'arg1', 'arg2'])
She who travels light — forgot something.

Return to “General discussion”