【问题标题】:linux find the command invokedlinux查找调用的命令
【发布时间】:2013-10-19 03:26:06
【问题描述】:

我正在编写一个 C 程序来确定从标准输入读取的字节数。我 发现有一些方法可以为程序提供输入

  • 管道输入
  • 重定向
  • 在程序等待输入时进入命令行

如何找到从 shell 执行程序的确切命令。 我尝试使用命令行参数但失败了。

#include <stdio.h>

int main(int argc,char *argv[])
{
        char buffer[100];
        int n;

        for(n=1;n<argc;n++)
                printf("argument: %s\t",argv[n]);

        printf("\n");
        if(argc==1)
                printf("waiting for input :");
        else if (argc==3)
                printf("Not waiting for input . Got the source from command itself .");

        n = read(0,buffer,100);
        if(n==-1)
                printf("\nError occured in reading");
        printf("\nReading successfully done\n");

        return 0;
}

还有,

【问题讨论】:

  • 你忘记在read之前调用fflush
  • 不清楚是否要计算程序或其他程序读取的字节数......

标签: c linux shell


【解决方案1】:

一般来说,您不能在程序内部执行此操作 - shell 可能不会将其中一些参数传递给您。在您的程序运行或获取参数之前,它将扩展 glob、完成 I/O 重定向等等。

您可以尝试拨打ps -o args,这可能对您有用。不过,据我所知,它不会提供重定向。

【讨论】:

    【解决方案2】:

    你有一些选项,检查 argv 以查看它是如何被调用的(argv[0] 来判断它是作为完整路径、相对路径、当前目录还是基于前面的 /s .s 使用 $PATH 或缺少)

    您可以通过以下方式获取调用它的父进程:

    sprintf(buf,"/proc/%d/cmdline",getppid());
    fd=open(buf,O_RDONLY);
    read(fd,buf,buf_size);
    write(1,buf,strlen(buf));
    

    您还可以从 /proc/pid/... 获取其他信息,用于使用上述 getpid(不是 getppid)的当前命令

    获得父进程后,您可能可以采取更多操作。例如,如果父级的基本名称是 sh 或 bash,您可以打开并读取历史文件,然后查找您的应用程序的出现。这将显示调用它的完整命令。其他应用程序可能有类似的历史文件。

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2018-05-04
      相关资源
      最近更新 更多