我在使用C语言设计一个命令行程序请问怎么在程序执行的时候在终端中输出日志的同时接收字符输入
可以使用多线程来实现同时输出日志和接收字符输入的功能。
主线程负责程序的执行,另开一个线程用来接收字符输入和输出日志。
示例代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *input_thread(void *arg)
{
char input[100];
while (1) {
printf("Input: ");
fgets(input, sizeof(input), stdin);
printf("You input: %s", input);
}
return NULL;
}
int main()
{
pthread_t tid;
if (pthread_create(&tid, NULL, input_thread, NULL) != 0) {
perror("pthread_create");
exit(1);
}
for (int i = 0; i < 10; i++) {
printf("i = %d\n", i);
}
if (pthread_join(tid, NULL) != 0) {
perror("pthread_join");
exit(1);
}
return 0;
}
在main函数中,我们新开一个线程来执行input_thread函数,该函数用来接收用户输入并输出日志。主线程执行完一定次数的循环后退出,并等待线程结束。
需要注意的是,由于input_thread函数中使用了stdio库的函数,因此需要在编译时加上参数“-pthread”来链接pthread库。例如:
gcc -o program program.c -pthread
``
原文地址: https://www.cveoy.top/t/topic/fpuB 著作权归作者所有。请勿转载和采集!