Find the answer to your Linux question:
Results 1 to 6 of 6
how to implement the following in C++ ls -l /proc/$$/exe. This gives the currently running shell....
  1. #1
    Just Joined!
    Join Date
    Oct 2007
    Posts
    15

    Implementing a command in C++

    how to implement the following in C++

    ls -l /proc/$$/exe.

    This gives the currently running shell.

  2. #2
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    The easiest way is to use the system() command.
    Check the manpage of system.

    Regards

  3. #3
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    Franklin52, system() is very useful, but I don't think that's HelloLinux's drift.

    HelloLinux, if you do the C++ equivalent of
    Code:
    ls -l /proc/$$/exe
    you won't get the currently running shell. You'll get the name of the currently running C++ program.

    Which do you want your C++ program to show? The currently running shell, or the currently running C++ program?

  4. #4
    Just Joined!
    Join Date
    Oct 2007
    Posts
    15
    It is suggested to avoid usage of System command.

    Is there any efficient way of doing it?

  5. #5
    Just Joined!
    Join Date
    Oct 2007
    Posts
    15
    I was looking forward to getting the currently running shell, which might have changed from default to some other shell

  6. #6
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    In a C or C++ program, you'll need to get your current pid by using getpid(). Once you have that, you can write a loop in which you repeatedly use the fourth field in /proc/processnumber/stat to get the parent process number. If you get process 1, you've gone too far.

    For each time through the loop, you can use readlink() on /proc/processnumber/exe to find the name of the program that process is running.

    The first time through the loop that you find that the name of the running program is found in file /etc/shells, that is the name of the shell you are runnning.

    I know that you said in a different thread that accessing /proc is time consuming, but the method I outlined is about as efficient as it gets.

    Hope this helps.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...