简体   繁体   English

C ++ _popen()/ system()在Windows上运行连续命令

[英]C++ _popen() / system() running consecutive commands on windows

I am working on a remote command prompt for a server of mine. 我正在使用我的服务器的远程命令提示符。 I am running into an issue with both _popen() and system() because once the command executes and the process will close/start a new instance (losing variables like active directory). 我遇到了_popen()system()的问题,因为一旦执行命令,进程将关闭/启动新实例(丢失活动目录之类的变量)。 I want to be able to run code like. 我希望能够运行类似的代码。

_popen("cd ..","r");
_popen("cd windwos","r");
_popen("dir","r");

I will also need a method of getting the pointed for the output text (this is why I started using _popen() . I am not sure if it is possible with _popen() , or I need to use something else. 我还将需要一种获取输出文本的指针的方法(这就是为什么我开始使用_popen() 。我不确定_popen()是否可行,或者我需要使用其他方法。

For changing directory, you will need to do that in the current process. 要更改目录,您需要在当前过程中执行此操作。 So you probably need a piece of code roughly like this: 因此,您可能需要一段大致像这样的代码:

if (cmd == "cd" || cmd == "chdir")
{
   chdir(argv[1]); 
}

The reason that running "cd" inside popen doesn't work is that it inly changes the directory in the CURRENT process. popen中运行“ cd”不起作用的原因是,它仅在CURRENT进程中更改了目录。 Making it change for the parent process would cause all manner of problems. 更改父流程会导致各种问题。

Of course, you may need to intercept a few other things, for example "set" (for environment variables), perhaps. 当然,您可能需要拦截其他一些内容,例如“ set”(针对环境变量)。

Just use a single command: dir ..\\windows\\ . 只需使用一个命令: dir ..\\windows\\ Or more verbose: cd .. && cd windows && dir 或更详细: cd .. && cd windows && dir

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM