在 PHP 中运行忘记系统调用的解决方案如下:
pcntl_fork()
函数:该函数允许在当前进程中创建一个新的子进程,从而允许您在不使用 exec()
的情况下运行子进程。<?php
function run_without_exec($command) {
$pid = pcntl_fork();
if ($pid == -1) {
// Fork failed
die('Could not create child process');
} elseif ($pid) {
// Parent process, do nothing
} else {
// Child process, run command
exec($command);
die('Command executed successfully');
}
}
// Example usage
run_without_exec('php -r "echo exec('ls -l');"')
? : run_without_exec('php -r "echo exec(whoami);"')
? : run_without_exec('php -r "echo exec('uname -a');"')
? : run_without_exec('php -r "echo exec('id');"')
? : run_without_exec('php -r "echo exec('ping 8.8.8.8');"')
? : run_without_exec('php -r "echo exec('curl http://www.example.com');"')
? : 'No commands executed';
<?php
namespace MyApp\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class RunCommandJob extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $command;
public function __construct($command)
{
parent::__construct();
$this->command = $command;
}
public function handle()
{
// Execute command
exec($this->command);
}
}
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class RunCommandJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $command;
public function __construct($command)
{
$this->command = $command;
}
public function handle()
{
// Execute command
exec($this->command);
}
}
在 Laravel 中,您可以在应用程序中创建一个新的作业,并将其添加到队列中,以便在需要时异步执行。您可以在 Artisan 命令行界面中使用 php artisan make:job
命令创建新的作业,然后将其添加到队列中,如以下示例所示:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class RunCommandJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $command;
public function __construct($command)
{
$this->command = $command;
}
public function handle()
{
// Execute command
exec($this->command);
}
}
在上面的代码中,我们使用 php artisan make:job
命令创建了一个新的作业,并将其命名为 RunCommandJob
。我们使用 $command
变量存储要执行的命令,并将其传递给作业构造函数。在 handle()
方法中,我们使用 exec()
函数执行命令。最后,我们将作业添加到队列中,以便在需要时异步执行。
现在,当您向队列中添加作业时,它将自动在后台运行,并执行指定的命令。
领取专属 10元无门槛券
手把手带您无忧上云