On Linux, the getcwd system call returns /home/foo/dir1 in your scenario.

#include <unistd.h> #include <stdio.h> #include <limits.h> int main() { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) == NULL) { perror("getcwd"); return 1; } printf("Current working dir: %s\n", cwd); return 0; }
[~/sym1]$ gcc -Wall -Wextra -pedantic a.c -o a && ./a Current working dir: /home/ikegami/dir1

It's not that bash sets the child's CWD differently than its own; /proc shows that bash's CWD is also resolved.

[~/sym1]$ readlink /proc/$$/cwd /home/ikegami/dir1

In fact, the system call to get the CWD returns the resolved link even if you explicitly set the CWD to the link.

#include <unistd.h> #include <stdio.h> #include <limits.h> int main() { if (chdir("/home/ikegami/sym1")) { perror("chdir"); return 1; } char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) == NULL) { perror("getcwd"); return 1; } printf("Current working dir: %s\n", cwd); return 0; }
[~/sym1]$ gcc -Wall -Wextra -pedantic a.c -o a && ./a Current working dir: /home/ikegami/dir1

What this means is that in no way is the process's CWD /home/ikegami/sym1 as you think. So short of trusting $ENV{PWD} to be accurate, it's simply impossible to get /home/ikegami/sym1 from the system since that's not the process's CWD.

use 5.010; use Path::Tiny qw( path ); say path($0)->absolute($ENV{PWD});
[~/sym1]$ perl a.pl /home/ikegami/sym1/a.pl

Do note that this is entirely insecure.

A setuid script that relies on unresolved links in $0 is insecure.
A setuid script that relies on $ENV{PWD} is insecure.

Seeking work! You can reach me at ikegami@adaelis.com


In reply to Re: Getting the absolute path of a script, without PWD by ikegami
in thread Getting the shell's version of working directory, without PWD's help by perlancar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.