【发布时间】:2017-09-25 19:02:49
【问题描述】:
我制作了一个程序,它使用fork() 函数来创建子进程。它的子进程做一些工作,但我希望它们在收到来自父进程的SIGTERM 信号时终止。在退出之前,我还希望他们清理我分配的数组并通过 FIFO 将一些东西发送到父进程。所以我有2个场景。
-
我的数组的全局变量以及 FIFO 的文件描述符,然后通过信号处理函数退出,例如:
/*global variables*/ struct whatever ** test; int test_size; int fd_in, fd_out; /*handler*/ void shutdown(int signo) { /*free memory for the arrays malloc'd through the program*/ /*send message with the help of fd_out*/ /*close fd_in and fd_out*/ _exit(0); } -
声明一个全局int标志,当子进程感知到标志发生变化时,它们会清理数组,发送消息并退出。
/*global variables*/ int exit_flag=0; /*handler*/ void shutdown(int signo) { exit_flag=1; } /*child process*/ int main() { /*declare fds and arrays*/ /*use sigaction and set up handler*/ while(!exit_flag) { /*do stuff*/ } /*free memory*/ /*send message with the help of fd_out*/ /*close fds*/ }
我的问题是哪种情况会导致良好的编码/编程?它们是相同的还是有更好、更正确的方法来做到这一点?
【问题讨论】:
标签: c signals signal-handling