Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling PHP ^C CLI Script

Tags:

php

signals

I have a php script that runs in the background 24/7. I have to occasionally terminate it, and the point of the script is to cache transaction data to memcahced from bitcoin RPC (if you don't know what that is, it is irrelevant). I want the script to execute a function when the program receives the signal sent on ^C (control C).

like image 362
macintosh264 Avatar asked Sep 22 '11 00:09

macintosh264


People also ask

Can PHP be used for command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

Can we use PHP to write command line scripts Yes?

The CLI SAPI differs from other PHP SAPIs and these differences are documented in PHP Command Line Usage: Differences to other SAPIs. PHP is not just for web pages and web sites anymore. It can be used for command line scripting as well.

How do I pass a command line argument in PHP?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

What is CLI version of PHP?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run. You can also configure the PHP version used when you call just the command php.


2 Answers

You probably want pcntl_signal. The signal you need to catch is SIGINT.

like image 147
Oliver Charlesworth Avatar answered Oct 05 '22 02:10

Oliver Charlesworth


In case anybody else is looking, I've found an answer that doesn't require pcntl_signal.

You can use system("stty intr ^-"); to stop ^C from exiting the script automatically. You can then capture it as ord(fread(STDIN, 1)) == 3 within PHP, and handle exiting manually.

I'm working on a library that does this.

like image 39
oranj Avatar answered Oct 05 '22 00:10

oranj