简体   繁体   English

linux找到被调用的命令

[英]linux find the command invoked

I am writing a C program which determines the number of bytes read from the standard input . 我正在编写一个C程序,该程序确定从标准输入读取的字节数。 I found out there are ways to give input to the program 我发现有一些方法可以输入程序

  • piped input 管道输入
  • redirection 重新导向
  • entering into command line while the program is waiting for input 在程序等待输入时进入命令行

How to find the exact command by which the program was executed from the shell . 如何从shell中查找执行程序的确切命令。 I tried using command-line arguments but failed . 我尝试使用命令行参数,但失败了。

#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;
}

Also , 还有,

In general, you can't do that from inside your program - the shell might not pass along some of those arguments to you. 通常,您不能从程序内部执行此操作-shell可能不会将其中的某些参数传递给您。 It will have expanded globs, done I/O redirection and so forth, all before your program ever runs or gets arguments. 在程序运行或获取参数之前,它将扩展glob,完成I / O重定向等操作。

You can try calling out to ps -o args , which might work out for you. 您可以尝试调出ps -o args ,这可能适合您。 It won't give redirections as far as I know, though. 据我所知,它不会进行重定向。

you have some options, check argv to see how it was invoked (argv[0] to tell whether it was invoked as full path, relative path, current directory or using $PATH based on preceding /s .s or lack thereof ) 您有一些选择,请检查argv以查看其调用方式(argv [0]以告知它是作为完整路径,相对路径,当前目录还是基于/ s .s或基于$ s的$ PATH调用)。

you can get the parent process that invoked it with something like: 您可以通过以下方式获取调用它的父进程:

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

you can also get other info from /proc/pid/... for the current command using getpid as above (not getppid) 您还可以使用上述getpid从/ proc / pid / ...获取当前命令的其他信息(不是getppid)

Once you get the parent process, you may be able to take more actions. 一旦获得父流程,您便可以执行更多操作。 For example if the basename of the parent is sh, or bash you can open and read the history file then find occurrences of your app. 例如,如果父级的基本名称是sh或bash,则可以打开并读取历史记录文件,然后查找应用程序实例。 That will show the full command that invoked it. 这将显示调用它的完整命令。 Other applications may have similar history files. 其他应用程序可能具有类似的历史记录文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM