【问题标题】:Linux C++ Detect user shell (csh,bash,etc)Linux C++ 检测用户 shell(csh、bash 等)
【发布时间】:2015-03-05 11:58:40
【问题描述】:

我有一个 C++ 应用程序,它需要使用系统调用来生成特定于 shell 的命令。有没有办法检测用户正在运行哪个 shell? (Csh/Bash/等)。

谢谢


详细说明

我正在尝试使用一些通过system 分叉的代码rsh 调用具有使用setenv 的命令序列,这在bash 中不起作用。我想检测系统是csh还是bash并相应地重写调用。

【问题讨论】:

  • 也许使用popen运行echo $SHELL?或echo $0?
  • 哪个用户?脚本之一或可能许多已登录的脚本之一?
  • 你签到/etc/passwd,例如:cat /etc/passwd | grep user | cut -d: -f7
  • @InnocentBystander 然后呢?当前的外壳在那里吗?没有
  • 不要system(不安全的)rsh 命令,而是fork 然后execve

标签: c++ linux bash shell


【解决方案1】:

不知道有没有用

#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/

【讨论】:

  • 编译正常。奇怪的路径也为空
  • @Jeef 如果您在命令行上键入 env 是变量之一 SHELL ?如果不是,是否有类似的东西
  • 不,它应该在那里,getenv 似乎是正确的答案......我将不得不更深入地研究我的具体构建。也许是时候清理一下了。
  • 这不能保证有效,很可能只适用于 bash。
【解决方案2】:

使用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("%s\n", getpwuid(geteuid())->pw_shell);
    return 0;
}

【讨论】:

    【解决方案3】:

    我未能获得 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]='\0';
                }
                fclose(f);
            }
        }
        return name;
    }
    
    bool isZshParentShell() {
        pid_t parentPid=getppid();
        const char* cmdline=get_process_name_by_pid(parentPid);
        return cmdline && strstr(cmdline, "zsh");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多