更新:這似乎是一個計時問題。在殺死呼叫之前添加一個呼叫進入睡眠狀態可以使所有事情按預期工作。發送和處理克隆線程上的信號
我一直在玩克隆(2),並試圖弄清它是如何工作的。我目前無法將信號發送到克隆進程。我有以下代碼:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
volatile int keep_going = 1;
typedef void (*sighandler_t)(int);
void handler(int sig) {
printf("Signal Received\n");
keep_going = 0;
}
int thread_main(void* arg) {
struct sigaction usr_action;
sigset_t block_mask;
sigfillset(&block_mask);
usr_action.sa_handler = &handler;
usr_action.sa_mask = block_mask;
usr_action.sa_flags = 0;
sigaction(SIGUSR1, &usr_action, NULL);
printf("Hello from cloned thread\n");
while(keep_going);
}
int main(int argc, char **argv) {
void* stack = malloc(4096);
int flags = SIGCHLD;
int child_tid = clone(&thread_main, stack + 4096, flags, NULL);
if (child_tid < 0) {
perror("clone");
exit(EXIT_FAILURE);
}
printf("My pid: %d, child_tid: %d\n", (int) getpid(), (int) child_tid);
int kill_ret = kill(child_tid, SIGUSR1);
if (kill_ret < 0) {
perror("kill");
exit(EXIT_FAILURE);
}
int status = 0;
pid_t returned_pid = waitpid(child_tid, &status, 0);
if (returned_pid < 0) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
exit(EXIT_SUCCESS);
}
其產生以下的輸出:
My pid: 14101, child_tid: 14102
killed by signal 10
孩子明顯打死作爲信號的結果,爲什麼信號處理程序不會被調用?
如果我在殺死的呼叫之前添加一個睡眠呼叫,它就可以工作。看起來這是一個計時問題。 – fido
問題:什麼程序,現在我已經找出了問題,並且不一定有答案給出答案?我應該編輯我的問題並以某種方式關閉它,或者創建我自己的答案並將其提供爲「接受的答案」? – fido