How to Store cmd memory in c++ using system(&#

2019-09-16 00:21发布

Look at the code below! You will understand what I want:

#include <iostream>
#include <windows.h>

    using namespace std;

    int main()
    {  
       system("set plock=24865");
       system("echo %plock%"); // I know this will not work.But How to make it work?

     return 0;
    }

2条回答
姐就是有狂的资本
2楼-- · 2019-09-16 00:56

Each system() invocation creates a separate environment then destroys it when it returns to your program. This is why they can not pass information between each other.

To set an environment variable for the environment of your program use the putenv() call and later read it with the getenv() call.

The system() call inherits a copy of the environment of the program which invokes it , so at least you can set variables using putenv() and have a program invoked by system() read them.

If you expect to invoke an external program using system() and get information back from it via environment variables you can not do this easily. If this is your goal consider using fork().

查看更多
【Aperson】
3楼-- · 2019-09-16 01:15

Well, as you say, that won't work. What's important to understand is why: The system call spawns a child process to run the shell, and then you're setting an environment variable in that child process, which promptly terminates.

So perhaps your question is over-specific in that it asks how to do this "using system()"; short answer is you can't. (Long answer is you could set the environment variable in the registry, but that's only sensible if you intend this to be a permanent configuration change to the computer. It's not the best idea if you just mean to set a variable for use in subsequent system() calls from the same program..)

So instead you could use the SetEnvironmentVariable() function, which will set the environment variable in your current process (instead of in a child that's about to go away).

UPDATE - There is one other option, alluded to in the question's comment thread; but it assumes that you can set the variable and immediately run any/all commands that depend on it right after. In the case where you can do that, you could pack all the commands into one system call, most simply with a batch script...

查看更多
登录 后发表回答