title: In python process, a C language function invoke python script method but cause segment error
body: <p>today I encounter a problem which is too difficult to me. In my project, python will load a C library and invoke a init function provided by C library, and in some case of python run, a function in C library will invoke a python script function to signal the python code that data comes and check it. I have write a demo to simulate the case, but then error occurs, below is my code:<br>
  <strong>C Library Code:</strong></p>
  
  <pre><code>#include &lt;test.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;Python.h&gt;
  #include &lt;string.h&gt;
  
  void sig_handler(int sig) {
    PyObject *p_name = NULL;
    PyObject *p_func = NULL;
    PyObject *p_args = NULL;
    PyObject *p_value = NULL;
    PyObject *p_module = NULL;
  
    char *module_name = "pyfunction";
    char *function_name = "c_py_function";
  
    Py_Initialize();
    PyGILState_STATE d_gstate;
    d_gstate = PyGILState_Ensure();
  
    p_name = PyUnicode_DecodeFSDefault(module_name);
    Py_DECREF(p_name);
  
    p_module = PyImport_Import(p_name);
    if (p_module != NULL) {
      p_func = PyObject_GetAttrString(p_module, function_name);
      if (p_func &amp;&amp; PyCallable_Check(p_func)) {
        p_value = PyObject_CallObject(p_func, p_args);
        if (p_value != NULL) {
          fprintf(stderr, "Result of call function %s is %ld\n", 
                  function_name, PyLong_AsLong(p_value));
          Py_DECREF(p_value);
          Py_Finalize();
        }
      } else {
        Py_DECREF(p_func);
        Py_DECREF(p_module);
  
        if (PyErr_Occurred())
          PyErr_Print();
        Py_Finalize();
  
        fprintf(stderr, "Call %s failed\n", function_name);
        abort();
      }
    } else {
      PyErr_Print();
      Py_Finalize();
  
      fprintf(stderr, "Failed to load python module %s\n", module_name);
      abort();
    }
  }
  
  int Init_c_base(void) {
    int ret = 0;
    struct sigaction new;
    struct sigaction old;
  
    sigemptyset(&amp;new.sa_mask);
    sigemptyset(&amp;new.sa_mask);
  
    new.sa_flags = 0;
    new.sa_handler = sig_handler;
  
    ret = sigaction(SIGUSR1, &amp;new, &amp;old);
    if (ret != 0) {
      return -1;
    }
  
    fprintf(stderr, "Finish init c environment base.\n");
    return 0;
  }
  </code></pre>
  
  <p><strong>Python Script code:</strong></p>
  
  <pre><code>import time
  import threading
  import concurrent.futures
  import run
  
  g_stop_run = 0
  
  def thread_fn_1():
      global g_stop_run
  
      while not g_stop_run:
          print("Thread %u is runing" % threading.get_ident())
          time.sleep(1)
      return 1
  
  def thread_fn_2():
      global g_stop_run
  
      while not g_stop_run:
          print("Thread %u is runing" % threading.get_ident())
          time.sleep(1)
      return 2
  
  def c_py_function():
      global g_stop_run
  
      print("Thread %u run, send exit signal." % threading.get_ident())
      g_stop_run = 1
  
  if __name__ == '__main__':
      run.Init_c_base()
      executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
  
      futures = []
      futures.append(executor.submit(thread_fn_1))
      futures.append(executor.submit(thread_fn_2))
  
      time.sleep(100)
      print("Thread execute result is:\n")
      for f in futures:
          print(f.result())
  
      print("Main thread is %u" % threading.get_ident())
  </code></pre>
  
  <p><strong>SWIG FILE:</strong></p>
  
  <pre><code>// run.i - Swig interface.
  %module run
  %{
  #include "test.h"
  %}
  
  extern int Init_c_base(void);
  </code></pre>
  
  <p>The C library code will compile to <code>.so</code> and enable python invoke via <code>SWIG</code>, and in my demo python first call <code>Init_c_base</code> in C library and the <code>Init_c_base</code> will registe a signal handler <code>sig_handler</code> of <code>SIGUSR1</code>. Then send <code>SIGUSR1</code> to python, the <code>sig_handler</code> run at once, but cause a segment fault.  </p>
  
  <p>bt of segment fault is:</p>
  
  <pre><code>(gdb) bt
  #0  0x00007f2b4667064a in convertsimple (arg=0x7f2b3f262cf0, p_format=p_format@entry=0x7fffe09b7b58, p_va=&lt;optimized out&gt;, flags=0, msgbuf=0x7fffe09b7d30 "p}\233\340\377\177", bufsize=bufsize@entry=512, 
      freelist=freelist@entry=0x7fffe09b7c20) at Python/getargs.c:1216
  #1  0x00007f2b46670a49 in convertitem (arg=arg@entry=0x7f2b3f262cf0, p_format=p_format@entry=0x7fffe09b7bf8, p_va=p_va@entry=0x7fffe09b7f78, flags=flags@entry=0, levels=levels@entry=0x7fffe09b7cb0, 
      msgbuf=msgbuf@entry=0x7fffe09b7d30 "p}\233\340\377\177", bufsize=bufsize@entry=512, freelist=freelist@entry=0x7fffe09b7c20) at Python/getargs.c:549
  #2  0x00007f2b466718b2 in vgetargskeywords (args=0x7f2b3b0c8410, keywords=0x0, format=0x7f2b467454bb "U|OOOi:__import__", kwlist=0x7f2b469e7ce0 &lt;kwlist.12206&gt;, p_va=p_va@entry=0x7fffe09b7f78, 
      flags=flags@entry=0) at Python/getargs.c:1739
  #3  0x00007f2b46672cb6 in PyArg_ParseTupleAndKeywords (args=&lt;optimized out&gt;, keywords=&lt;optimized out&gt;, format=format@entry=0x7f2b467454bb "U|OOOi:__import__", kwlist=kwlist@entry=0x7f2b469e7ce0 &lt;kwlist.12206&gt;)
      at Python/getargs.c:1363
  #4  0x00007f2b46648090 in builtin___import__ (self=&lt;optimized out&gt;, args=&lt;optimized out&gt;, kwds=&lt;optimized out&gt;) at Python/bltinmodule.c:235
  #5  0x00007f2b465a3822 in PyCFunction_Call (func=0x7f2b46bef508, args=0x7f2b3b0c8410, kwds=0x0) at Objects/methodobject.c:98
  #6  0x00007f2b46544463 in PyObject_Call (func=0x7f2b46bef508, args=0x7f2b3b0c8410, kwargs=kwargs@entry=0x0) at Objects/abstract.c:2261
  #7  0x00007f2b465447c6 in call_function_tail (callable=callable@entry=0x7f2b46bef508, args=args@entry=0x7f2b3b0c8410) at Objects/abstract.c:2512
  #8  0x00007f2b46544ec7 in PyObject_CallFunction (callable=callable@entry=0x7f2b46bef508, format=format@entry=0x7f2b4674d908 "OOOOi") at Objects/abstract.c:2539
  #9  0x00007f2b466772c0 in PyImport_Import (module_name=0x7f2b3f262cf0) at Python/import.c:1767
  #10 0x00007f2b3aeb7b8b in sig_handler (sig=10) at test.c:24
  #11 &lt;signal handler called&gt;
  #12 0x00007f2b458da0d3 in __select_nocancel () at ../sysdeps/unix/syscall-template.S:81
  #13 0x00007f2b466db876 in pysleep (secs=100000000000) at ./Modules/timemodule.c:1467
  #14 0x00007f2b466db929 in time_sleep (self=&lt;optimized out&gt;, obj=&lt;optimized out&gt;) at ./Modules/timemodule.c:235
  #15 0x00007f2b465a35fc in _PyCFunction_FastCallDict (func_obj=func_obj@entry=0x7f2b3f26c490, args=args@entry=0x19088b8, nargs=nargs@entry=1, kwargs=kwargs@entry=0x0) at Objects/methodobject.c:209
  #16 0x00007f2b465a3a67 in _PyCFunction_FastCallKeywords (func=func@entry=0x7f2b3f26c490, stack=stack@entry=0x19088b8, nargs=nargs@entry=1, kwnames=kwnames@entry=0x0) at Objects/methodobject.c:294
  #17 0x00007f2b4664d287 in call_function (pp_stack=pp_stack@entry=0x7fffe09b9198, oparg=oparg@entry=1, kwnames=kwnames@entry=0x0) at Python/ceval.c:4851
  #18 0x00007f2b46657382 in _PyEval_EvalFrameDefault (f=0x1908728, throwflag=&lt;optimized out&gt;) at Python/ceval.c:3335
  #19 0x00007f2b4664c3bb in PyEval_EvalFrameEx (f=f@entry=0x1908728, throwflag=throwflag@entry=0) at Python/ceval.c:754
  #20 0x00007f2b4664ce5f in _PyEval_EvalCodeWithName (_co=0x7f2b3f286c40, globals=&lt;optimized out&gt;, locals=&lt;optimized out&gt;, args=&lt;optimized out&gt;, argcount=argcount@entry=0, kwnames=0x0, kwargs=kwargs@entry=0x0, 
      kwcount=kwcount@entry=0, kwstep=kwstep@entry=2, defs=defs@entry=0x0, defcount=defcount@entry=0, kwdefs=kwdefs@entry=0x0, closure=closure@entry=0x0, name=name@entry=0x0, qualname=qualname@entry=0x0)
      at Python/ceval.c:4166
  #21 0x00007f2b4664d4da in PyEval_EvalCodeEx (_co=_co@entry=0x7f2b3f286c40, globals=globals@entry=0x7f2b46b27c88, locals=locals@entry=0x7f2b46b27c88, args=args@entry=0x0, argcount=argcount@entry=0, 
      kws=kws@entry=0x0, kwcount=kwcount@entry=0, defs=defs@entry=0x0, defcount=defcount@entry=0, kwdefs=kwdefs@entry=0x0, closure=closure@entry=0x0) at Python/ceval.c:4187
  #22 0x00007f2b4664d524 in PyEval_EvalCode (co=co@entry=0x7f2b3f286c40, globals=globals@entry=0x7f2b46b27c88, locals=locals@entry=0x7f2b46b27c88) at Python/ceval.c:731
  #23 0x00007f2b46684979 in run_mod (mod=mod@entry=0x18ed3d0, filename=filename@entry=0x7f2b3f2627b0, globals=globals@entry=0x7f2b46b27c88, locals=locals@entry=0x7f2b46b27c88, flags=flags@entry=0x7fffe09b9540, 
      arena=arena@entry=0x7f2b3f264220) at Python/pythonrun.c:1025
  #24 0x00007f2b46687644 in PyRun_FileExFlags (fp=fp@entry=0x1924ae0, filename_str=filename_str@entry=0x7f2b3f2641f0 "pyfunction.py", start=start@entry=257, globals=globals@entry=0x7f2b46b27c88, 
      locals=locals@entry=0x7f2b46b27c88, closeit=closeit@entry=1, flags=flags@entry=0x7fffe09b9540) at Python/pythonrun.c:978
  #25 0x00007f2b46687a0e in PyRun_SimpleFileExFlags (fp=fp@entry=0x1924ae0, filename=&lt;optimized out&gt;, filename@entry=0x7f2b3f2641f0 "pyfunction.py", closeit=closeit@entry=1, flags=flags@entry=0x7fffe09b9540)
      at Python/pythonrun.c:419
  #26 0x00007f2b46687bcf in PyRun_AnyFileExFlags (fp=fp@entry=0x1924ae0, filename=0x7f2b3f2641f0 "pyfunction.py", closeit=closeit@entry=1, flags=flags@entry=0x7fffe09b9540) at Python/pythonrun.c:81
  #27 0x00007f2b466a028d in run_file (fp=fp@entry=0x1924ae0, filename=filename@entry=0x18a72c0 L"pyfunction.py", p_cf=p_cf@entry=0x7fffe09b9540) at Modules/main.c:340
  #28 0x00007f2b466a0f3a in Py_Main (argc=argc@entry=2, argv=argv@entry=0x18a6010) at Modules/main.c:810
  #29 0x0000000000400b6d in main (argc=2, argv=0x7fffe09b96b8) at ./Programs/python.c:69
  </code></pre>
  
  <p>I am very confused about this problem, and I wonder whether python support the case I encounter, and could you please tell me how to solve this problem if support?</p>