0

First of all use windows.

I have the following code:

index.php

<?php
    error_reporting(E_ALL);
    $tiempo_inicio = microtime(true);
    exec('C:\wamp\bin\php\php5.5.12\php.exe -e C:\wamp\www\mail.php  > /dev/null &');  
    $tiempo_fin = microtime(true);
    echo ($tiempo_fin - $tiempo_inicio);
    ?>

Mail.php

<?php
$tiempo_inicio = microtime(true);
    $logs = fopen("test.txt","a+"); 
    sleep(2);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    "); 
    sleep(4);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    ");
    sleep(6);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    ");
    echo 'fin';
?>

But it does not work I hope, because what I want is to run the file in the background without the user wait for the completion of this file.

What am I doing wrong?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Luis Ramos
  • 73
  • 1
  • 5
  • 1
    I think & to run process in background is linux . Although i am not a windows user but i think that it is where you are going wrong. Also a better method would rather that calling `&` make a process queue and assign workers to that. That way if the background job is heavy there is less chances of server crashing – georoot Apr 15 '16 at 11:44

2 Answers2

1

You're talking about a non-blocking execution (where one process doesn't wait on another. PHP really can't do that very well (natively anyways) because it's designed around a single thread. Without knowing what your process does I can't comment on this precisely but I can make some suggestions

  • Consider asynchronous execution via AJAX. Marrying your script to a Javascript lets the client do the request and lets your PHP script run freely while AJAX opens another request that doesn't block the activity on the main page. Just be sure to let the user visually know you're waiting on data
  • pthreads (repo)- Multi-threaded PHP. Opens another process in another thread.
  • Gearman - Similar to pthreads but can be automated as well
  • cron job - Fully asynchronous. Runs a process on a regular interval. Consider that it could do, say, data aggregation and your script fetches on the aggregate data
Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
0

I've had success in the past on Windows using pclose/popen and the Windows start command instead of exec. The downside to this is that it is difficult to react to any errors in the program you are calling.

I would try something like this (I'm not on a machine to test this today):

$command_string = 'C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\mail.php" -- variablestopass';

pclose(popen("start /B ".$command_string, 'r')); 
Machavity
  • 30,841
  • 27
  • 92
  • 100
DMartins
  • 26
  • 1
  • 4