-1

I want to convert an uploaded PDF file to JPG images and zip these images after convert process finishes. I use the ImageMagick library's convert command for PDF to JPG conversion.

To accomplish this, I use the && operand like this:

convert /tmp/asdassa_1395994117.pdf -density 200 /tmp/files/asdassa_1395994117.pdf.jpg && zip -r /tmp/files/files.zip /tmp/files/* &

This command works just fine except one thing: It runs on the foreground so the server doesn't respond until it finishes.

If I use either one of these commands by adding & at the end of the command, it runs on the background and I can get the response asap. But when using together, it doesn't.

Is there something that I'm missing? Might it be about the command type? Because testing the && and & operands with simple commands like sleep and mkdir works on the background as I expect to be, for example this command:

sleep 10 && mkdir bla &

Goes to the background and creates the bla dir after 10 seconds.

P.S. My server runs on Amazon Linux AMI 2013.03

Edit: It turned out that the problem wasn't about the OS but the exec() function of PHP. Please check my answer to see how I worked it out.

kubilay
  • 159
  • 1
  • 3
  • 12
  • Given the examples provided, I cannot duplicate the problem behaviour. – Matthew Ife Mar 28 '14 at 08:43
  • @MatthewIfe Okay, one more detail. I'm using PHP's exec() function. Do you think it will matter? – kubilay Mar 28 '14 at 08:56
  • 1
    Yes, yes, we do. And congratulations on figuring it out (seriously, +1 for that). But **please** consider this a learning experience in writing a good question: don't **tell** us what you think are the important bits of what you're doing, **show** us in as much detail as possible. Otherwise, you may well miss out the key element, the one that leads to the answer. – MadHatter Mar 28 '14 at 09:28

1 Answers1

2

So it turned out that the problem wasn't about how I was using the commands but how I was using the commands from PHP.

I was doing it like this:

exec($command);

However, I then found out that the exec() command doesn't like these kind of usage. So instead of passing the command directly, I decided to put the command to a temporary .sh file and use it in exec() instead.

// create the command, don't forget to delete the temporary file with a last command
$command = "convert /tmp/asdassa_1395994117.pdf -density 200 /tmp/files/asdassa_1395994117.pdf.jpg && zip -r /tmp/files/files.zip /tmp/files/* && rm /tmp/temp.sh";

// create file with this command
exec("echo '".$command."' > /tmp/temp.sh");

// execute on the background with output
exec("sh /tmp/temp.sh > /dev/null 2>&1 & echo $!");

This works well.

kubilay
  • 159
  • 1
  • 3
  • 12