在 C 中处理信号、管道和分支
Messing with signals, pipes and forks in C
如何让进程在不终止的情况下监听用户输入? .因此,例如,我希望 bash 等待 X 分钟,如果我说 "stop" 它退出,或者只是继续等待......我该如何实现?因此,在执行时,我的进程会等待,然后我希望能够通过标准输入停止、暂停或继续,键入 "stop"、"continue" 或“暂停。谢谢。
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;
}
一个简单(但浪费)的选项是初始程序分叉然后等待输入。子进程可以更新计数器。
当父程序接收到 "pause" 时,它向子程序发送信号 SIGTSTP。
当父程序接收到 "continue" 时,它向子程序发送信号 SIGCONT。
当父程序接收到 "stop" 时,它向子程序发送信号 SIGQUIT。
如果需要,您还可以使用 sigaction 在父级中设置一个 SIGINT 处理程序,当您键入 Ctrl+C 时,它会杀死子级。
如何让进程在不终止的情况下监听用户输入? .因此,例如,我希望 bash 等待 X 分钟,如果我说 "stop" 它退出,或者只是继续等待......我该如何实现?因此,在执行时,我的进程会等待,然后我希望能够通过标准输入停止、暂停或继续,键入 "stop"、"continue" 或“暂停。谢谢。
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;
}
一个简单(但浪费)的选项是初始程序分叉然后等待输入。子进程可以更新计数器。
当父程序接收到 "pause" 时,它向子程序发送信号 SIGTSTP。
当父程序接收到 "continue" 时,它向子程序发送信号 SIGCONT。
当父程序接收到 "stop" 时,它向子程序发送信号 SIGQUIT。
如果需要,您还可以使用 sigaction 在父级中设置一个 SIGINT 处理程序,当您键入 Ctrl+C 时,它会杀死子级。