How to obtain the file name of the current executable file in Linux

Source: Internet
Author: User

In many cases, we place the resource file in the relative location of the executable file, for example, with the executable file. Therefore, it is necessary to obtain the absolute path of the current executable file and then find the path of the resource file.

In Windows, you can use getmodulefilename to obtain the name of the current executable file, but in Linux, this situation becomes more complex.

First, I have not found a similar function. I can only use argv [0] to obtain the executable file name. In Linux, there is a disgusting and cute link/Symbol link. For example, you can convert/usr/local/evol3d/demo.exe ln into/usr/bin/ev-bin. At this time, you will be dumpfounded to execute ev-bin.

After several days of consultation, I finally found a simple method:

1. When the current program is running, you can read/proc/self/EXE, which is a connection to the executable file of the current process. This link points to a result similar to getmodulefilename. I would like to thank my former male colleague, the beautiful Fang girl.

2. readlink function. readlink can convert the connection name to the actual file name.

 

Note: This method is purely created by an individual and tested correctly on the machine. If any, please kindly advise.

The Code is as follows.

STD: String _ exename = "/proc/self/EXE ";
Size_t linksize = 256;
Char exename [256] = {0 };
If (readlink (_ exename. c_str (), exename, linksize )! =-1)
{
_ Exename = exename;
}

Printf ("application file name = % s! /N ", _ exename. c_str ());

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.