0

I have the following script and corresponding C program which at first glance appear to work the same with respect to signals and the standard error output.

Script:

#!/bin/sh

function terminate() {
   printf "stopped" >&2
   exit 0
}

printf "started" >&2
trap terminate SIGINT SIGTERM
sleep infinity

C program:

#include <stdio.h>
#include <signal.h>

static volatile int terminating = 0;

void terminate(int _) {
    terminating = 1;
}

int main(void) {
   signal(SIGINT, terminate);
   signal(SIGTERM, terminate);   
   fprintf(stderr, "started");
   while(!terminating);
   fprintf(stderr, "stopped");
   return 0;
}

Now, when I run either the C program or the script (after adding execute permission) from my terminal, I get the expected behavior as follows: (1) started is printed to stderr, (2) I send a SIGINT using Ctrl-C, (3) stopped is printed to stderr, (4) the process terminates with exit status 0.

However, when I run these programs from Python using create_subprocess_exec, I find that while the C programs behaves as it did when I ran it from the terminal, the script only gets as far as printing started and doesn't seem to receive the signal. I would like to know what are the differences in how signals are being handled/routed in these two cases.

Update

I was trying to make the script more like the C program and swapped out the sleep infinity for a dumb busy-wait while true; do sleep 0.1; done. After doing this, the script now behaves the same regardless of whether I run it from the terminal or from the Python function.

mallwright
  • 432
  • 2
  • 10

0 Answers0