编写linux下c语言程序,模拟命令行输入界面,以root用户时用#,其它用户时用>
时间: 2024-03-05 15:51:22 浏览: 190
下面是一个简单的Linux下C语言程序,用于模拟命令行输入界面:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#define MAX_COMMAND_LENGTH 1024
int main(void) {
char command[MAX_COMMAND_LENGTH];
struct passwd *pw = getpwuid(getuid());
char *username = pw->pw_name;
char *prompt = ">";
if (getuid() == 0) {
prompt = "#";
}
while (1) {
printf("%s%s ", username, prompt);
if (fgets(command, MAX_COMMAND_LENGTH, stdin) != NULL) {
system(command);
} else {
break;
}
}
return 0;
}
```
程序中,我们通过`getuid()`函数获取当前登录用户的ID,如果ID为0,则说明当前用户为root用户,此时将提示符设为`#`,否则设为`>`。
在程序的主循环中,我们使用`fgets()`函数读取命令行输入,并使用`system()`函数执行输入的命令。
运行该程序后,即可模拟一个命令行输入界面,其中root用户的提示符为`#`,其它用户的提示符为`>`。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)