Using the exec() family to run the “cd” command

后端 未结 5 2031
醉酒成梦
醉酒成梦 2020-12-07 01:30

I know that cd is a shell built-in ,and I can run it by using system().

But is that possible to run the cd command by the

5条回答
  •  执笔经年
    2020-12-07 02:02

    While, as already stated system("cd xxx") wouldn't change your application current directory, it is not completely useless.

    You can still use system exit status to know if changing your current directory to the one stated would succeed or not.

    Similarly, if you like complex solutions, you could also do the same with fork/exec, either with exec'ing /bin/sh -c cd xxx or simply /bin/cd xxx with OSes that provide an independent cd executable.

    I would however recommend this non overkill faster equivalent access("xxx", X_OK|R_OK)

    Note: All POSIX compliant OSes must provide an independent cd executable. This is at least the case with Solaris, AIX, HP-UX and Mac OS/X.

提交回复
热议问题