실행파일이 위치한 디렉터리를 찾는 함수가 있을까요?

simpid의 이미지

안녕하세요.

프로그램 개발하다보니... 실행되고 있는 프로그램이 자기 자신이 어디있는지 알아야 하는데 어떤 함수를 써야 할지 모르겠습니다.

검색을 해봐도.. ^^; 알 수 가 없고..

아시는분 답변 부탁드립니다.

익명 사용자의 이미지

언어는요?

익명 사용자의 이미지

제가 아는것만.

c의 경우에는

int main(int argc,char **argv){
return 0;
}

argv[0]에 프로그램의 이름을 가집니다.

하지만 perl의 경우에는 @ARGV 에 프로그램 이름을 가지고 있지 않고,인자들만을 가지고 있습니다.(그래서 저는 그냥 __FILE__ 을 씁니다 --;)

대부분은 c의 경우와 비슷합니다.

simpid의 이미지

C언어 사용합니다.

argv[0]을 사용할 경우..

./a.out 의 형식으로 실행하거나 하면 정확한 패스를 알 수 없습니다. 풀 패스가 필요한 상황이거든요.

제가 Windows 프로그래밍에 익숙한 상황이라.
GetModuleFileName() 같은 함수가 필요합니다.

뭐 없을까요?

ssik425의 이미지

man getcwd

개발자들의 궁극적 비전은 ?

익명 사용자의 이미지

getcwd로 작업디렉터리 패쓰를 구한후 조합하심이 어떨지.

dreamstorm의 이미지

저도 이게 궁금하네요 ( 제경우는 C/C++ 입니다 )

제가 프로그램을 짤때, 설정파일을 만들어서 실행 바이너리와 같은
위치에 두고 읽어들이곤 하는데, win32 에서는 GetModuleFileName 이란 API 가 있어서
간단히 가져올수 있었지만 유닉스쪽에서는 방법을 모르겠더군요

바이너리가 있는 path 에서 ./a.out 해서 실행했다면야 getcwd 해서 쓰면 되지만
다른 디렉토리에서 실행을 했거나, 또는 환경변수 PATH 에 의해서 실행이 됐다면
getcwd 나 argv 만으론 알기가 까다롭고.. getcwd 와 argv, PATH 까지 모두 뒤진다면
찾아낼수 있을것 같긴 한데 설정파일 하나 찾자고 그런 코딩 하는건 좀 귀찮군요. :oops:

지금은 설정파일위치를 환경변수로 읽거나, 실행시 인자로 받고 있는데
그냥 코드 안에서 자기자신의 위치를 찾아낼 포터블한 방법이 없을까요?

ssik425의 이미지

좋은 방법은 아니지만 system("pwd")값을 popen으로 열어 가져오는
방법은 어떤가요?

개발자들의 궁극적 비전은 ?

whitekid의 이미지

realpath()가 있군요..

      1 #include <stdio.h>
      2 #include <sys/param.h>
      3 #include <stdlib.h>
      4 
      5 int main(char *argc, char *argv[])
      6 {
      7     char resolved_path[MAXPATHLEN];
      8 
      9     printf("%s, %s\n", argv[0], __FILE__);
     10     realpath(argv[0], resolved_path);
     11     printf("resolved_path: %s\n", resolved_path);
     12     
     13     return 0;
     14 }

$ ./a.out
./a.out, test.c
resolved_path: /usr/home/whitekid/a.out

What do you want to eat?

익명 사용자의 이미지

stat 쓰는데 경로가 안먹혀서 애를 먹었는데

덕분에 해결했습니다 감사합니다~ ^^

최종호의 이미지

realpath 가 재밌긴 하지만 argv[0] 에 들어온 값이
상대경로나 절대경로가 아닌 경우에는 유용하지 않을 수도 있는듯 합니다.

예를 들면,
현재 디렉토리가 $HOME/work 이고
path에 잡혀있는 $HOME/bin 에 있는 realpath 라는 프로그램을
% realpath
라고 수행시키는 경우에는 argv[0] 에는 realpath 만이 들어갈텐데,
realpath() 함수로 "realpath" 가 어디에 있는지 알아낼 수는 없죠.

argv[0]가 상대경로나 절대경로로 주어진 경우에는 realpath()를 사용하고,
그렇지 않은 경우에는 PATH 설정을 쫒아가면서 찾아야 할 듯 합니다.

정태영의 이미지

Quote:
aqua@cafri ~ $ which ls
/usr/bin/ls
aqua@cafri ~ $ whereis ls
ls: /bin/ls /usr/bin/ls /usr/X11R6/bin/ls /usr/bin/X11/ls /usr/man/man1/ls.1.gz /usr/man/man1p/ls.1p.gz /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

패쓰안에 있을경우엔 저렇게 찾을 수 있기는 합니다 =3=33

오랫동안 꿈을 그리는 사람은 그 꿈을 닮아간다...

http://mytears.org ~(~_~)~
나 한줄기 바람처럼..

neohwang의 이미지

main의 argv[0] 값을 dirname, basename 등으로 잘 처리해 보시고,
만약 디렉토리 패스가 전혀없을 경우에는 추가적으로
PATH 환경변수를 검색하는 루틴도 추가 하셔야 완벽합니다.

neohwang의 이미지

아.. 추가적으로 환경변수를 getenv("PATH") 함수로 구해서
디렉토리를 검사할때, 해당 파일이 실행권한을 가지고 있는지도 확인해야 됩니다.

익명 사용자의 이미지

디렉토리 모두를 제귀적으로 훑어볼 경우 ftw함수가 유용합니다.

익명 사용자의 이미지

http://www.mail-archive.com/linux-development-sys@senator-bedfellow.mit.edu/msg01424.html

http://lists.linux.org.au/archives/tuxcpprogramming/2004-October/msg00010.html

From: Erik de Castro Lopo <[EMAIL PROTECTED]>
Subject: Re: GetModuleFileName() in linux
Date: Fri, 14 Jul 2000 12:42:38 +0000

Eric Co wrote:
>
> hi,
> in windows, we can use GetModuleFileName() to retrieve the full path and
> filename for the executable file.
> how to do it in linux?

This is possible but is usually not a good idea and Not The Way Its
Done In Unix (tm). Usually the only reason to do something like this
is to find the location of configuration files, data files or extra
libraries. For these purposes, this is a very bad idea.

Global configurations files should be placed in /etc, per-user
configuration files should be in the user's home directory.

Extra libraries should go in something like /usr/local/lib/
or /usr/local/lib/app-name/.

Application specific data files should be placed in a directory
like /usr/local/share/app-name/.

However, if you don't want to heed my very good advice and you really,
really want to do this, you can, by reading the psuedo file
"/proc/self/maps".

Erik
--
+-------------------------------------------------+
Erik de Castro Lopo [EMAIL PROTECTED]
+-------------------------------------------------+
I hack, therefore I am.

Jack Lloyd wrote:
Actually, if your application is built with a hard-coded library path, it's
possible you won't find a library you're linked against in LD_LIBRARY_PATH or
/etc/ld.so.conf.

You can try using dladdr(), but it's somewhat tricky to use. It works,
sometimes, but often the path you get back is relative instead of absolute,
lots of stupid little problems like that.

-Jack

On Thu, Oct 21, 2004 at 08:08:10PM -0300, Adriano dos Santos Fernandes wrote:

Hi All!

In Windows is possible to discover the path of a DLL in the entry-point,
using GetModuleFileName with the HINSTANCE of the DLL.

I knew one way to do this in Linux. Using the LD_LIBRARY_PATH
environment variable and looking for the filename.

Is there a better way to do this?
If not, the correct way to do is only look for files in LD_LIBRARY_PATH
environment variable or have other directories to find too?

Adriano

초코리의 이미지

이런식으로 하면될것 같습니다..
리눅스에서만 테스트 한것이라
/proc의 구조가 다르다면 잘모르겠습니다 ^^::

#include <stdio.h>
#include <string.h>
int main(void)
{
    char arBuf[256];
 
    memset(arBuf, 0x00, sizeof(arBuf));
 
    readlink("/proc/self/exe", arBuf, 256);
 
    fprintf(stderr,"arBuf[%s]\n", arBuf);
 
    return 0;
}

kulblade의 이미지

IBM AIX에서는

sprintf(id, "/proc/%d/cwd", getpid());
printf("%s\n", id);
readlink(id, path, 256);

어떤 곳에서는

sprintf(id, "/proc/%d/exe", getpid());
printf("%s\n", id);
readlink(id, path, 256);

로 찾아야 하는 것 같습니다.

프로그램이 죽기전에 /proc 디렉토리를 들어가서 어떤 파일에서 symbolic link를 사용해야 하는지 확인해야 할 것 같습니다.

jinserk의 이미지

저도 이런 함수가 C++ 에서 필요한데,
도저히 모르겠네요. 답글을 살펴봤지만 전부 마땅한 방법같지는 않고..

제가 짜는 프로그램이 linux, cygwin, msvc 에서 돌려야 되는 넘이다보니
어쨌든 세 환경에서 잘 돌아가길 바라는데요,
실행 파일이 담겨진 경로를 얻어낼 수 있는 보편적인 방법은 없는걸까요?

Leo.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.