Linux C++ 检测用户外壳(csh,bash等)

Linux C++ Detect user shell (csh,bash,etc)

本文关键字:bash csh C++ 检测 用户 外壳 Linux      更新时间:2023-10-16

我有一个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");
}