多进程启动时功能不起作用

Function does not work when started by multiprocess

我有一个 C 函数分配一个整数,在 returning 指针之前将指针传递给回调函数。

void change_state(int gpio, int level, uint32_t tick, void *ptr){
    if (level == 1){
        printf("Button was pressed!\n");
        *((int*)ptr) += 1;
    }
}

int * allocate_void_ptr_start_watchdog(int BUTTON){
    void *current_state_ptr = malloc(sizeof(int)); /*Creates a ptr of size int*/
    *((int*)current_state_ptr) = 0; /*Casts ptr to type int and set to 0*/
    gpioSetAlertFuncEx(BUTTON, change_state, current_state_ptr); /*Function to watch for GPIO state change*/
    return current_state_ptr; 
}

然后将 return 值传递回 Python:

allocate_ptr_start_watchdog = button_functions.allocate_void_ptr_start_watchdog
allocate_ptr_start_watchdog.restype = ctypes.POINTER(ctypes.c_int)
ptr = allocate_ptr_start_watchdog(BUTTON)

按如下方式使用 while True 循环按预期工作(在 GPIO 25 按下 1 次按钮将打开灯,第二次按下将关闭灯)

while True:
    current_val = ptr.contents.value
    if current_val == 0:
        continue
    elif current_val == 1:
        button_functions.turn_on_lights(LED_1, LED_2)
    else:
        button_functions.clear_all(LED_1, LED_2)
        ptr.contents.value = 0

然而,一旦我尝试使用多处理功能中断,因为按下按钮不再打开或关闭灯。但是,C 库中的 printf 仍然打印,所以我怀疑这是库的问题。

def button_start(ptr):
    while True:
        current_val = ptr.contents.value
        if current_val == 0:
            continue
        elif current_val == 1:
            button_functions.turn_on_lights(LED_1, LED_2)
        else:
            button_functions.clear_all(LED_1, LED_2)
            ptr.contents.value = 0


multiprocessing.Process(target=button_start, args=(ptr,)).start()

这是 运行 Raspbian Buster,内核为 5.10.63-v7l+。我 missing/failing 在这里看到什么?

由于 MP 进程需要连接回 pigpio 守护进程,因此需要一个函数来执行该操作。

int connect_to_daemon(){ /*Connect to pigpio daemon*/
    printf("Connecting to daemon\n");
    int daemon_instance = pigpio_start("192.168.86.234", NULL);
    printf("Successfully connected to daemon\n");
    return daemon_instance;
}

然后我们可以在 Python daemon_instance = button_function.connect_to_daemon() 中为这个实例分配一个变量,然后再调用我们的回调函数。

int * start_callback(int daemon_instance, int BUTTON){
    void *current_state_ptr = malloc(sizeof(int)); /*Creates a ptr of size int*/
    *((int*)current_state_ptr) = 0; /*Casts ptr to type int and set to 0*/
    callback_ex(daemon_instance, BUTTON, FALLING_EDGE, change_state, current_state_ptr);
    return current_state_ptr;
}

在Python中:

ptr = button_functions.start_callback(daemon_instance, BUTTON)
print(ptr.contents.value)  # This should return the correct value now

非常感谢 2e0byo!