题目
众所周知,游戏都有暂停功能,请利用 fork() 函数创建父子进程,其中一个隔一秒打印一段文字(模拟运行的游戏),另外一个接收键盘的输入,并发送信号暂停与继续游戏(例如可以按 ’s’ 键暂停,按 ’c’ 键继续)。
提示:1) 自行思考父子进程中,哪个模拟游戏,哪个接收输入并发送信号。2) 自行查找发送什么信号 “暂停”,什么信号 “继续”。
源代码
#include <iostream>
#include <signal.h>
#include <unistd.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
pid_t pid = fork();
if (pid > 0) {
system("/bin/stty raw");
for (int c; c != 't'; ) {
c = getchar();
switch (c) {
case 's':
kill(pid, SIGSTOP);
break;
case 'c':
kill(pid, SIGCONT);
break;
case 't':
kill(pid, SIGTERM);
break;
}
}
system("/bin/stty cooked");
}
else if (pid == 0) {
for (;;) {
puts("The game is running.");
sleep(1);
}
}
else {
puts("Fork ERROR.");
return 1;
}
}