调用 powershell 脚本时未使用 c++ 系统 api 设置错误号

Errno is not set using c++ system api while invoking powershell script

我正在使用 system api 来调用 powershell 脚本并且该脚本没有将 errno 设置为任何值,如果命令执行则不会给我提示是成功还是失败。

下面是我的 powersehll 脚本,它只是设置退出代码,但是当我使用 c++ 系统调用这个脚本时,这个退出代码没有设置 api。

测试.ps1

#-------------------------------------------------------------------------------
function ExitWithCode {
#-------------------------------------------------------------------------------
  param($exitcode)
  $host.SetShouldExit($exitcode);
  exit
}
ExitWithCode -exitcode 1

使用c++程序执行脚本

        string cmd = "";
        std::getline(cin, cmd);
        errno = 0;
        cout <<" system " <<cmd << "  ------> " << endl;
        cout << system(cmd.c_str()) << " errno " << errno << endl;

c++程序的输出

powershell -ExecutionPolicy Unrestricted -File "C:\test.ps1"
system   powershell -ExecutionPolicy Unrestricted -File "C:\test.ps1"  ------>
0 errno 0

系统命令输出为 0 但 errno 也设置为 0。知道为什么没有设置 errno 吗?

PowerShell 中的 exit 关键字默认将 return 代码设置为 0。由于您只是在不带参数的情况下调用 exit,因此 return 代码将始终为 0。将您的功能更改为:

#-------------------------------------------------------------------------------
function ExitWithCode {
#-------------------------------------------------------------------------------
  param($exitcode)
  exit $exitcode
}
ExitWithCode -exitcode 1

或者不要重新发明轮子,直接调用:

exit 1