【问题标题】:How do I use _spawnvpe() with a custom PATH value?如何将 _spawnvpe() 与自定义 PATH 值一起使用?
【发布时间】:2012-06-20 13:45:27
【问题描述】:

我在 (http://stackoverflow.com/questions/10969488/why-does-windows-spawn-process-sometimes-trigger-error-status-sxs-assembly-not-f) 中提出了一个相关问题但我担心它会被问题的复杂性弄糊涂,所以,这里有一个非常简单的版本:

这是一个调用 _spawnvpe 的示例,手动传递 PATH 值。

它不起作用。它出错并且不会运行记事本。

更改为 _spawnv 或不传递 PATH 值使其工作。但是,_putenv 的文档清楚地说明了 env 值的格式是 KEY=VALUE。

如何让它发挥作用?

请具体说明,并提供以下代码的差异或完整副本,包括修复。

#include <stdio.h>
#include <windows.h>
#include <process.h>
#include <errno.h>

int main(int argc, char *argv[]) {

  char *path_value;
  char buffer[4000];
  const char *env[2];
  const char *args[1];
  char *command;
  int result;
  intptr_t procHandle;

  path_value = getenv("PATH");
  sprintf(buffer, "PATH=%s", path_value);
  env[0] = buffer;
  env[1] = NULL;

  args[0] = NULL;

  int offset = 0;
  while (env[offset] != NULL) {
    printf("env %d: %s\n", offset, env[offset]);
    ++offset;
  }

  offset = 0;
  while (args[offset] != NULL) {
    printf("arg %d: %s\n", offset, args[offset]);
    ++offset;
  }

  command = "C:\\windows\\system32\\notepad.exe";

  procHandle = _spawnvpe(_P_NOWAIT, command, args, NULL);
  if (procHandle == -1) {
    printf("Failed to invoke command: %s\n", strerror(errno));
    exit(1);
  }

  _cwait(&result, procHandle, 0);
  if (result != 0)
    printf("Command exited with error code %d\n", result);
}

【问题讨论】:

  • 请务必使用调试版本,它会为您提供此代码的断言。 argv[0] 不能为 NULL,它必须指向 exe 路径。
  • 您甚至没有在此处显示的_spawnvpe 调用中使用env

标签: c windows spawn


【解决方案1】:

以下代码对我有用(仅显示更改的行):

...
const char *args[2];
...
args[0] = "notepad.exe";
args[1] = NULL;
...
procHandle = _spawnvpe(_P_NOWAIT, command, args, env);
...

Visual Studio 2010、Windows HPC Server 2008 R2。

请注意,Windows 会在 PATH 中搜索程序 AND 动态库,而大多数 Unix 系统的可执行文件和库路径具有单独的变量。

【讨论】:

  • ^____^ 你让我很开心。谢谢!
猜你喜欢
  • 2017-11-09
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 2012-04-01
相关资源
最近更新 更多