Linux C++ 检测用户外壳(csh,bash等)
Linux C++ Detect user shell (csh,bash,etc)
我有一个C++应用程序,需要使用系统调用来制作特定于 shell 的命令。 有没有办法检测用户正在运行哪个 shell? (Csh/Bash/等)。
谢谢
精巧
我正在尝试使用一些代码,这些代码通过system
rsh
调用进行分叉,该调用具有一系列使用setenv
的命令,这些命令在 bash 中不起作用。 我想检测系统是csh
还是bash
,并相应地重写调用。
获取带有 geteuid
的用户 ID,获取该 ID getpwuid
包含 shell 且不得释放的用户数据库条目。所以它分解为
getpwuid(geteuid())->pw_shell
最小工作示例:
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
int main (int argc, const char* argv[]) {
printf("%sn", getpwuid(geteuid())->pw_shell);
return 0;
}
不知道这是否有用
#include <iostream>
#include <cstdlib> /* getenv */
int main ()
{
char* Shell;
Shell = getenv ("SHELL");
if (Shell!=NULL)
std::cout << Shell << std::endl;
return 0;
}
将输出类似于
/bin/bash
Getenv 返回一个带有环境变量值的 c 字符串。
链接:http://www.cplusplus.com/reference/cstdlib/getenv/
我未能获得BASH_VERSION/ZSH_VERSION/...环境变量,因为它们不会导出到子进程;/etc/passwd 提供了登录 shell,因此获取我找到的当前 shell 的唯一方法是:
const char* get_process_name_by_pid(const int pid)
{
char* name = (char*)calloc(256,sizeof(char));
if(name){
sprintf(name, "/proc/%d/cmdline",pid);
FILE* f = fopen(name,"r");
if(f){
size_t size = fread(name, sizeof(char), 256, f);
if(size>0){
if('n'==name[size-1])
name[size-1]=' ';
}
fclose(f);
}
}
return name;
}
bool isZshParentShell() {
pid_t parentPid=getppid();
const char* cmdline=get_process_name_by_pid(parentPid);
return cmdline && strstr(cmdline, "zsh");
}
相关文章:
- 将bash参数传递给c++
- bash脚本在使用popen()时不返回代码以调用C ++程序
- 终端如何在 shell 提示符下以编程方式阻止退格,以便您无法在其上退格,例如 $ 表示 bash 或 C:\blah\>
- Bash 自动完成一个选项,而不运行应用程序
- 在 Windows 上运行带有 C++ 的 bash 脚本
- 使用 bash 脚本和测试处理进行代码编辑
- 主机箱/bash 未执行 docker 映像
- 如何在 bash 中使用管道在 c++ 中使用 getenv() 访问文件?
- 终端(bash)如何知道引发了什么异常
- -bash:/a.out:无法执行二进制文件:Exec格式错误
- 在 Bash 脚本中处理来自子进程的信号
- 将字符串变量从 bash 脚本传递到根宏
- 有没有办法在 C 或 C++ 中嵌入 Sh/Bash 会话?
- 如何将C++输出捕获到 Bash 变量?
- Bash run 命令在子壳的后台运行
- 从C++代码中以字符串形式运行多行 bash 脚本
- 在字符串流的 SSH 命令中转义 bash 脚本中的引号
- 如何使用 std::in 和 getline() 检测后台进程中从 bash 注入的输入
- Bash 脚本和命令行参数
- Linux C++ 检测用户外壳(csh,bash等)