开发者

change directory with pipe in UNIX

I am writing a C program that basically is supposed to change directory 开发者_高级运维and call another program. I have tried :

system("cd ... | ./test.exe");

but it doesn't seem to work.


Surely, you wanna do:

cd /this/is/a/dir && ./command


try:

system("cd ... ; ./test.exe");

(I'm assuming ... is a placeholder for your directory).

If that doesn't work, consider creating a short script (call it script.sh):

#!/bin/sh
cd ...
./test.exe

then execute

system("./script.sh");


I'm going to ignore the use of the system function, and answer as if the pipeline command was typed at the command line, for the sake of making this point:

When you create a pipeline like cd somedir | ./test.exe, the shell is allowed to run each command of the pipeline in a separate subshell environment. Furthermore, there's no guarantee that they'll execute in strict left-to-right order. So the cd command doesn't affect the environment of test.exe in the way you're expecting. cd, being a shell builtin, can only affect the environment of the shell it's executed in, which in this case would be a subshell created as part of setting up the pipeline, not the shell into which the pipeline command was typed.


"cd" is not going to work with a pipe. Try something like:

chdir("/path");
system("./test.exe");


I'd use

system("cd .. && ./test.exe");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜