在Linux平台上编写一个C语言应用程序,采用多进程的方法,实现下列两个任务并行: 1)每隔1秒在屏幕上打印出自己的中文姓名; 2)如果在键盘上按1键,打印出自己的学号;如果按2键,打印出自己的班级;如果按q键,则打印停止,程序结束;按其余键无效。
时间: 2024-05-02 20:16:42 浏览: 12
下面是一个简单的实现方式:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <termios.h>
void print_name(int signum);
void print_info(char input);
int main(void) {
pid_t pid;
int fd;
struct termios oldt, newt;
// 创建子进程
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) {
// 子进程打印姓名
signal(SIGALRM, print_name);
alarm(1);
while (1) {
pause();
}
} else {
// 父进程等待用户输入
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
fd = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(fd, F_SETFL, fd | O_NONBLOCK);
while (1) {
char c = getchar();
if (c != EOF) {
print_info(c);
}
}
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}
return 0;
}
void print_name(int signum) {
printf("姓名:YourName\n");
alarm(1);
}
void print_info(char input) {
switch (input) {
case '1':
printf("学号:YourID\n");
break;
case '2':
printf("班级:YourClass\n");
break;
case 'q':
printf("停止\n");
exit(0);
break;
default:
break;
}
}
```
在程序中,父进程负责等待用户输入,并根据不同的输入打印出相应的信息,子进程负责每隔1秒钟在屏幕上打印出姓名。为了实现非阻塞读取用户输入,我们需要将终端的输入模式设置为非标准模式,这里使用了 `tcgetattr` 和 `tcsetattr` 函数实现。同时,为了避免用户输入时阻塞程序,我们将文件描述符 `STDIN_FILENO` 设置为非阻塞模式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)