简体   繁体   中英

linux find the command invoked

I am writing a C program which determines the number of bytes read from the standard input . 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 . 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. It will have expanded globs, done I/O redirection and so forth, all before your program ever runs or gets arguments.

You can try calling out to ps -o args , which might work out for you. 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 )

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)

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. That will show the full command that invoked it. Other applications may have similar history files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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