search
HomeBackend DevelopmentPHP Tutorial PHP借用$cmd运行程序后,怎么关闭

PHP借用$cmd运行程序后,如何关闭?
我想用PHP运行某exe程序(不要CRON等计划程序,PHP里还有其他内容。这里方便测试,以记事本为例),在其打开3秒后,执行关闭。
如何操作?
是否可以调用任务管理器将其关闭?求解决代码。谢谢。

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><?php $cmd = 'C:\WINDOWS\system32\notepad.exe';
system($cmd);
sleep(3);
//$cmd1 = 'C:\WINDOWS\system32\taskmgr_original.exe';
//system($cmd1);
?>


------解决方案--------------------
PHP code

<?php $handle = popen('C:\WINDOWS\system32\notepad.exe', "r");
pclose($handle);
?>
<br><font color="#e78608">------解决方案--------------------</font><br>popen ― 打开进程文件指针<br><br>说明<br>resource popen ( string $command , string $mode )<br>打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。  <br><br>返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets(),fgetss() 和 fwrite()。  <br><br>如果出错返回 FALSE。  <br><br>Note:  <br><br>如果需要双向支持,使用 proc_open()。  <br><br><br><br>Example #1 popen() 例子<br><br><?php <br />$handle = popen("/bin/ls", "r");<br>?>  <br><br>Note:  <br><br>如果未找到要执行的命令,会返回一个合法的资源。这看上去很怪,但有道理。它允许访问 shell 返回的任何错误信息:  <br><br><?php <br />error_reporting(E_ALL);<br><br>/* 加入重定向以得到标准错误输出 stderr。 */<br>$handle = popen('/path/to/spooge 2>&1', 'r');<br>echo "'$handle'; " . gettype($handle) . "\n";<br>$read = fread($handle, 2096);<br>echo $read;<br>pclose($handle);<br>?>  <br><br><br>
<br><font color="#e78608">------解决方案--------------------</font><br>
探讨
PHP code

$handle = popen('C:\WINDOWS\system32\notepad.exe', "r");
pclose($handle);
?>

------解决方案--------------------
popen返回的是notepad.exe在php环境下的进程指针,这个指针只能用于读取和输出数据给notepad,pclose关闭的只是这个指针而不是notepad本身.

我也不清楚如何关闭notepad,但是我想应该从windows的编程基础中查找如何获取任务管理器中的进程,然后用system函数去调用windows的关闭程序
------解决方案--------------------
popen是单向的,用proc_open吧
试试看
PHP code
/**
 * windows only
 */
$descriptorspec = array(   
    0 => array("pipe", "r"), 
    1 => array("pipe", "w")
);
$cwd = 'C:\WINDOWS\system32';
$process = proc_open('notepad.exe', $descriptorspec, $pipes, $cwd);
$s          = proc_get_status( $process );//得到的信息都是父进程cmd.exe的状态,而非子进程notepad.exe的.所以不能直接kill掉这个process id
sleep( 3 );
exec('taskkill /PID '.$s['pid'] . ' /T'); //树型删除,删除所有父进程与对应的子进程.原来以为子进程id必定大于父进程,写了一通代码,后来发现不是,且找到了这个命令
proc_close( $process ); <div class="clear">
                 
              
              
        
            </div>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools