0

作为我无法启动 SRCDS(Source 游戏引擎的专用服务器)故障排除的一部分,我决定尝试启动其他一些可执行文件(特别是 Chrome 和 Firefox)。然而,这些都没有推出。页面已加载(没有像 SRCDS 那样挂起),但在检查 Windows 任务管理器时,这些进程从未真正启动。$output 是一个长度为 0 的数组, $return_var 是 1 (没有给我关于发生的实际错误的信息。

我使用的代码是(使用systemorpassthru代替时没有变化exec):

<?php
// Save the current working directory, then set it to SRCDS' directory
$old_path = getcwd();
chdir("C:/Users/Johan/Desktop/SteamCMD/tf2/");

// Launch SRCDS. Only the 3rd exec allows the page to load.
//$tmp = exec("srcds -console -game tf +map ctf_2fort 2>&1",$output,$output2);
//$tmp = exec("srcds -console -game tf +map ctf_2fort >> tmp.txt",$output,$output2);
$tmp = exec("srcds -console -game tf +map ctf_2fort 1>/dev/null/ 2/&1",$output,$output2);
echo "<p>SRCDS Output: ".sizeof($output)."</p>";
echo "<p>SRCDS Output2: ".$output2."</p>";

// Test execution of other files
// test.bat echoes %time%
$tmp2 = exec("test.bat");
echo $tmp2;
// Trying to launch another executable
chdir("C:\Program Files (x86)\Mozilla Firefox");
$tmp2 = exec("firefox", $output, $output2);
echo $tmp2;
echo "<p>FF Output:".sizeof($output)."</p>";
echo "<p>FF Output2:".$output2."</p>";

// End
chdir($old_path);
echo "Done.";
?>

这输出:

SRCDS Output: 0

SRCDS Output2: 1

0:47:59,79
FF Output:0

FF Output2:1

Done.

我的问题是,这有什么理由吗?我做错了吗?

4

1 回答 1

0

看起来你是:

  • 在 Windows 上
  • 尝试异步启动外部程序

这是让你这样做的秘诀:

function async_exec_win($cmd)
{
    $wshShell = new COM('WScript.Shell');
    $wshShell->Run($cmd, 0, false); // NB: the second argument is meaningless
                                    // It just has to be an int <= 10
}

这要求COM该类对您的 PHP 实例可用,您可能需要extension=php_com_dotnet.dll在 php.ini 中启用(自 PHP 5.3.15/5.4.5 起)才能使其可用。

另请注意,这将需要您希望执行的文件的完整文件名,因为扩展名搜索列表不会在 cmd.exe 之外使用。所以不是srcds -console ...你想要srcds.exe -console ...- 我个人不喜欢这种chdir()方法,我宁愿将 exe 的完整路径传递给函数 - 但如果你这样做,你需要确保目录分隔符是操作系统的正确类型。PHP 会让你随心所欲地使用任何你喜欢的东西,操作系统不会那么宽容。

为了完整起见,这里是如何在 *nix 上做类似的事情。这实际上比 Windows 版本更好,因为它还返回创建的进程的 PID:

function async_exec_unix($cmd)
{
    return (int) exec($cmd . ' > /dev/null 2>&1 & echo $!');
}

需要注意的一点:您的命令必须正确转义。这些实现都没有对正在执行的命令执行任何验证,它们只是盲目地运行它。永远不要将用户输入传递给外部程序而不将其转义到主机操作系统!

于 2013-07-09T23:09:22.623 回答