在Linux平台上编写一个C语言应用程序,采用多进程的方法,实现下列两个任务并行:
1)每隔1秒在屏幕上打印出自己的姓名;
2)如果在键盘上按1键,打印出自己的学号;如果按2键,打印出自己的班级;如果按q键,则打印停止,程序结束;按其余键无效。
在Linux平台上编写一个C语言应用程序,采用多进程的方法,实现下列两个任务并行:
1)每隔1秒在屏幕上打印出自己的姓名;
2)如果在键盘上按1键,打印出自己的学号;如果按2键,打印出自己的班级;如果按q键,则打印停止,程序结束;按其余键无效。
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define your_name "王建国"
#define your_num 123
#define your_class "一班"
bool run=true;
void *pth_a(void *pth_agr)
{
while(run)
{
printf("姓名:%s\n",your_name);
sleep(1);
}
}
void *pth_b(void *pth_agr)
{
while(run)
{
int inputnum[8]={0};
scanf("%s",inputnum);
if(strcmp(inputnum,"1")==0)
{
printf("学号:%d\n",your_num);
}
else if(strcmp(inputnum,"2")==0)
{
printf("班级:%s\n",your_class);
}
else if(strcmp(inputnum,"q")==0)
{
printf("程序退出\n");
run=false;
}
else
{
printf("输入无效,请重新输入\n");
}
}
}
int main(int argc,char **argv)
{
pthread_t pid1;
pthread_t pid2;
pthread_create(&pid1,NULL,pth_a,NULL);
pthread_create(&pid2,NULL,pth_b,NULL);
while(run)
{
sleep(1);
}
return 0;
}
测试结果
没问题请点赞采纳哦,