简体   繁体   English

Linux / C如何正确结束命令行程序

[英]Linux/C How to properly end command line program

I have a program that runs on the Linux command line. 我有一个在Linux命令行上运行的程序。 It allocates some memory, opens some file descriptors, etc. I'd like a good way to be able to have user input stop the program while still doing cleanup and not interrupting some file read/write. 它分配一些内存,打开一些文件描述符,等等。我希望有一个好的方法,能够让用户输入在仍然进行清理的同时停止程序,并且不中断某些文件的读/写。 What is the proper way to do this? 正确的方法是什么? So far, I've been using CTRL+C to stop the program, but I feel like that doesn't do the cleanup properly, and that doesn't give my program the chance do a log file write indicating that it is closing. 到目前为止,我一直在使用CTRL + C来停止程序,但是我觉得那不能正确地进行清理,并且这也没有给我的程序写日志文件的机会,表明它已关闭。 Currently I'm doing this: -Set STDIN to non-blocking (So that the program doesn't hang waiting for input) 目前,我正在这样做:-将STDIN设置为非阻塞(这样程序就不会挂起等待输入)

while(loop_variable != 'q') {
loop_variable = getchar();
...
}

Any suggestions? 有什么建议么?

William Pursell commented that you can catch SIGINT. 威廉·珀塞尔William Pursell)评论说,您可以抓住SIGINT。

Here's how you would implement cleanup when SIGINT is caught. 当捕获SIGINT时,这是实现清除的方法。

First, you define the cleanup function. 首先,定义清理功能。 In the function you do all the house cleaning. 在此功能中,您需要进行所有房屋清洁。

void cleanup(int signum) {
    ... //all house cleaning steps like deleting files, closing file descriptors
}

In the main() function, you can call signal() and pass the name of the function cleanup and the associated signal to catch. 在main()函数中,您可以调用signal()并传递函数清除的名称和要捕获的关联信号。 You can catch as many types of signal appropriate for your user actions. 您可以捕获适合用户操作的多种信号。

signal(SIGINT, cleanup);
signal(SIGQUIT, cleanup);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM