1

I have a simple program that I run from a terminal which changes the working directory (via setCurrentDir) and performs some other work which creates some new files in that folder. When the program has completed, I would like the terminal prompt to remain in that folder rather than return to the original directory.

As far as I know, this is a linux issue, rather than a Nim issue, but I am wondering if there is any workaround in Nim.

sgmoore
  • 15,694
  • 5
  • 43
  • 67
  • 2
    There is no way for a subprocess to affect the current working directory of the parent. – larsks Mar 24 '22 at 12:04
  • 1
    The best you could do would be to run the program from within a script, have the program leave the desired directory someplace that the script can pick it up from, and have the script (which is hopefully running in the shell which is the parent process) read it in and do a cd. Or have your program open a shell which is a child of itself, but that risks the user piling up an ugly stack of shells; not recommended in most cases. The same answer applies to changing the parent's environment variables or other parent-task properties. – keshlam Mar 24 '22 at 17:20

1 Answers1

1

This should not be possible, and indeed isn't, without hacking the parent process using gdb in accordance with How do I set the working directory of the parent process?

Indeed, Do Not Do This.

import std/[os,osproc,strformat]

proc getppid():int32{.importc,header:"unistd.h".}

let f = open("/tmp/gdb_cmds",fmWrite)
f.write(&"""p (int) chdir ("{commandLineParams()[0]}")
detach
quit
""")
f.close()

discard execCmd(&"sudo gdb -p {getppid()} -batch -x /tmp/gdb_cmds;rm /tmp/gdb_cmds")

usage:

/tmp$ nim c cd.nim
/tmp$ mkdir child
/tmp$ touch you_are_in_parent_dir
/tmp$ touch child/you_are_in_child_dir
/tmp$ ls
you_are_in_parent_dir
cd.nim
cd
child
/tmp$ ./cd child
/tmp$ ls #<---notice pwd is cached
you_are_in_child_dir
/tmp$
shirleyquirk
  • 1,527
  • 5
  • 21