【问题标题】:grant permission to execute .c file授予执行 .c 文件的权限
【发布时间】:2015-09-14 04:26:12
【问题描述】:

我通过以下代码创建了一个文件

$dir = '/home/srikanth/Desktop';
 if ( !file_exists($dir) ) {
  mkdir ($dir, 0777);
 }
//$code contains the code C code which i want to execute
 file_put_contents ($dir.'/test.c', $code);
$path = "/home/srikanth/Desktop/test.c";
$Command = "gcc $path 2&>1";
exec($Command,$return_val,$error);

当我打开我的错误日志文件时 我看到以下错误

sh: 1: cannot create 1: Permission denied
gcc: error: 2: No such file or directory

我尝试了以下命令来更改权限,我目前使用的是 Ubuntu 14.04.2 和 Apache 服务器

chmod 0777 /home/srikanth/Desktop/test.c
sudo chmod -R 777 /home/srikanth/Desktop/test.c




sudo usermod -aG www-data root
addgroup www-data

我使用这些命令将 www-data 添加到根组 但我仍然继续在我的错误日志中获取相同的文件

【问题讨论】:

  • 来自cannot create .. Permission denied,错误很可能是因为 php/apache 用户无权在该目录中创建文件,这意味着 gcc 的输出。使用su "phpuser"; touch php-file.txt 验证这一点,对于 apache 也是如此
  • 将test.c文件放到你的项目中,运行一次php文件,因为有时它无法访问其他文件,而不是www文件夹
  • 感谢@Tamil Selvan,但我得到“无法创建 /var/www/html/test.c”/var/www/html 是我放置 php 文件的目录,而且当我尝试更改路径 /var/www/html 的权限我得到“chmod:更改'/var'的权限:不允许操作”
  • 我已经为我的文件提供了@AlexAndrei 上面提到的权限

标签: php ubuntu permissions exec


【解决方案1】:

如 cmets 中所述,此问题是权限问题,因为服务器用户无法在 /home/srinkanth/Desktop 目录中创建文件夹/文件。或者 gcc 编译器中的某些东西在你的 c 代码编译期间无法创建文件。

将 777 添加到该目录(不是单独的测试文件)可能会解决问题。但是,良好的做法是在代码中添加退出/异常,以便您更清楚地了解问题是否发生、何时发生以及导致问题的原因。

这是我的建议:

$dir = '/home/srikanth/Desktop';
if (!is_dir($dir)) {
    $mkDir = mkdir($dir, 0777);
    if (!$mkDir) {
        exit('Failed to create ' . $dir);
    }
}

然后你可以在你的 put 文件代码中添加额外的调试信息:

$codePath = $dir.'/test.c';
$created = file_put_contents($codePath, $code);
if (!$created) {
    exit('Failed to create ' . $codePath);
}

如果你到达这个阶段更多的是你的执行文件代码:

$codePath = $dir . '/test.c';
$command = "gcc $codePath 2&>1";

$output = [];
$returnStatus = '';
$lastLine = exec($command, $output, $returnStatus);

然后您可以通过将输出数组片段与新行粘合在一起来输出整个 gcc 编译,因为 exec 将输出的每一行解析为输出数组中的记录:

echo implode("\n", $output);

希望这会有所帮助。 祝你好运。

【讨论】:

  • 感谢@DanBelden,但我收到以下错误“sh: 1: cannot create 1: Permission denied gcc: error: 2: No such file or directory”
  • 这是您正在运行的代码的最终输出吗? gcc好像提示文件不存在?您能否确认 test.c 已创建并包含您需要的代码?这样你就可以看到你的代码在哪里失败而没有错误。
  • 感谢@danbelden 使用我的终端我尝试运行代码,它的工作正常 test.c 是在给定路径中创建的,它包含代码
  • 在这种情况下,这是 100% 的权限问题尝试创建一个新目录,例如 /home/srikanth/test 并设置权限 777 (chmod 777 /home/srikanth/test) 然后修改您的代码匹配新的目录路径并运行它。看看那是什么问题。从 PHP 运行 exec 开始涉及 PHP 用户、路径和许多其他变量,这些变量可能对您的 bash 变量产生奇怪的影响。祝你好运!
猜你喜欢
  • 2011-09-25
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2013-06-07
  • 2011-09-01
  • 1970-01-01
  • 2018-12-20
相关资源
最近更新 更多