为什么PHP的Shell_exec没有给出某些A.Out文件的输出

Why shell_exec of php is not giving output of some a.out file

本文关键字:文件 输出 Out Shell PHP exec 为什么      更新时间:2023-10-16

我正在使用一个可以编译并运行C 代码的PHP脚本。正在编译最大种类的C 代码,并通过Shell_Exec命令给出输出。但是某些具有结构的C 代码正在编译,但无法通过Apache Server中的Shell_exec从A.Out文件中获取输出。结果,它的输出显示为php中的零。注意到,在Ubuntu终端中可以工作,但是当我从PHP运行它时,它无法运行。我正在ubuntu,Apache Server上运行它。这是我的PHP代码,可以运行C 代码

<?php
$CC="g++";
$out="timeout 5s ./a.out";
$code=$_POST["code"];
$input=$_POST["input"];
$filename_code="main.cpp";
$filename_in="input.txt";
$filename_error="error.txt";
$executable="a.out";
$command=$CC." -lm ".$filename_code;    
$command_error=$command." 2>".$filename_error;
$check=0;
//if(trim($code)=="")
//die("The code area is empty");
$file_code=fopen($filename_code,"w+");
fwrite($file_code,$code);
fclose($file_code);
$file_in=fopen($filename_in,"w+");
fwrite($file_in,$input);
fclose($file_in);
exec("chmod -R 777 $filename_in");
exec("chmod -R 777 $filename_code");  
exec("chmod 777 $filename_error");  
shell_exec($command_error);
exec("chmod -R 777 $executable");
$error=file_get_contents($filename_error);
$executionStartTime = microtime(true);
if(trim($error)=="")
{
    if(trim($input)=="")
    {
        $output=shell_exec($out);
    }
    else
    {
        $out=$out." < ".$filename_in;
        $output=shell_exec($out);
    }
    //echo "<pre>$output</pre>";
          echo "<textarea id='div' class="form-control" name="output" rows="10" cols="50">$output</textarea><br><br>";
}
else if(!strpos($error,"error"))
{
    echo "<pre>$error</pre>";
    if(trim($input)=="")
    {
        $output=shell_exec($out);
    }
    else
    {
        $out=$out." < ".$filename_in;
        $output=shell_exec($out);
    }
                    echo "<textarea id='div' class="form-control" name="output" rows="10" cols="50">$output</textarea><br><br>";
}
else
{
    echo "<pre>$error</pre>";
    $check=1;
}
$executionEndTime = microtime(true);
$seconds = $executionEndTime - $executionStartTime;
$seconds = sprintf('%0.2f', $seconds);
echo "<pre>Compiled And Executed In: $seconds s</pre>";

if($check==1)
{
    echo "<pre>Verdict : CE</pre>";
}
else if($check==0 && $seconds>3)
{
    echo "<pre>Verdict : TLE</pre>";
}
else if(trim($output)=="")
{
    echo "<pre>Verdict : WA</pre>";
}
else if($check==0)
{
    echo "<pre>Verdict : AC</pre>";
}
exec("rm $filename_code");
exec("rm *.o");
exec("rm *.txt");
exec("rm $executable");
?>

通过终端运行时,您将在用户许可的情况下执行PHP脚本。但是,在使用Apache运行脚本时,您是在www-data用户下运行脚本。某些可执行文件无法在www-data用户下运行。您可以尝试的一种解决方案是将www-data添加到您的用户组。

您可以在https://unix.stackexchange.com/a/127529

上找到有趣的阅读

终于找到了我的解决方案。我刚将我的G 版本更改为4.9,然后Shell_exec()开始工作。

安装G 4.9

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.9

设置G 4.9

sudo ln -f -s /usr/bin/g++-4.9 /usr/bin/g++

无法显示先前显示输出的C 结构和类代码现在显示输出。我不知道为什么在终端G 5版本工作,但在shell_exec()中不起作用,但是G 4.9在终端和shell_exec()

中都在工作。