Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between exec and popen

Tags:

linux

php

I want to run an external PHP file on my server I found out that I can use either exec or popen.

I read that popen is used for Windows while, exec is used for Linux.

On the other hand I saw examples where popen can also be used for Linux. I am still a newbie. Is it possible? Which do you recommend for Linux if both exec and popen work?

Kindly what are the advantages as I am still confused.

like image 477
user2333968 Avatar asked Aug 21 '14 10:08

user2333968


2 Answers

If you just need to exec an external app, use exec() or shell_exec(). popen() is used if you need a pointer, which is something similar to what fopen() does with files. fopen() just opens the pointer to file, nothing else. Then you need other functions (fread(), fwrite()) to actually work with the file.

The same logic applies to popen().

exec() or shell_exec() can be used on windows as well as linux.

like image 188
Rikudou_Sennin Avatar answered Oct 01 '22 14:10

Rikudou_Sennin


In my case, I am using popen to run asynchronous php script from an Apache web app. I was trying exec, shell_exec and pclose(popen(...)) and the only one that creates a new process and execute it asynchronously is popen. All the others wait for the script to be finish before answering to browser.

My configuration is CentOS7, PHP 5.4.16 and Apache 2.4, haven't tried on Windows.

like image 21
Ivan Avatar answered Oct 01 '22 12:10

Ivan