简体   繁体   English

用C处理信号,管道和前叉

[英]Messing with signals, pipes and forks in C

How can I get the a process to listen for user input without terminating? 我如何才能获得一个监听用户输入而不终止的进程? . So, for example, i want the bash to wait for X minutes, and if i say "stop" it quits, or else just keeps waiting... How can I achieve that? 因此,例如,我希望bash等待X分钟,如果我说“停止”,它就退出了,否则就一直等待...我该如何实现? So, upon execution my process would wait , and then I want to be able to stop, pause or continue through stdin, typing "stop", "continue" or "pause. Thank you. 因此,执行后,我的过程将等待,然后我希望能够通过stdin停止,暂停或继续,键入“停止”,“继续”或“暂停”。谢谢。

C piece of code, responsible of reading the user actions ( TESTED ): C代码段,负责读取用户操作( TESTED ):

int main()
{
    /* start function */
    char choice;
    while(1)
    {
        printf("Enter s (stop), c (continue) or p (pause): ");
        scanf("%c",&choice);
        /* protect against \n and strings */
        while(choice != '\n' && getchar() != '\n'); 

        switch(choice) {
            case 's' :
                printf("Stop!\n" );
                /* stop function */
                return 0;
            break;
            case 'c' :
                printf("Go on!\n" );
                /* resume function */
            break;
            case 'p' :
                printf("Pause!\n" );
                /* pause function */
            break;
            default :
                printf("What?\n" );
            break;
        }
    }
    return 0;
}

A simple (but wasteful) option is that the initial program forks and then wait for input. 一个简单(但很浪费)的选项是初始程序派生然后等待输入。 The child process can update the counter. 子进程可以更新计数器。

When the parent program receive "pause" it sends the signal SIGTSTP to the child. 当父程序收到“暂停”时,它将信号SIGTSTP发送给子程序。

When the parent program receive "continue" it sends the signal SIGCONT to the child. 当父程序接收到“ continue”时,它将信号SIGCONT发送给子程序。

When the parent program receive "stop" it sends the signal SIGQUIT to the child. 当父程序收到“停止”消息时,它将信号SIGQUIT发送给子程序。

If you want, you can also set a SIGINT handler in the parent using sigaction that kills the child when you type Ctrl+C. 如果需要,还可以在父级中使用sigaction设置SIGINT处理程序,当您按Ctrl + C时会杀死子级。

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

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