Method of setting process name in PHP Cli mode

  • 2021-12-12 03:51:42
  • OfStack

Recently, I have been optimizing my PHP multi-process management tool. GitHub Address:

After being started by command, the name of its running in the background of the system is as follows:

[root@localhost logs]# ps -ef|grep "Event/register"
root 1358 1356 0 19:50 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1482 1358 0 19:55 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1483 1358 0 19:55 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1484 1358 0 19:55 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1486 1358 0 19:55 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1487 1358 0 19:55 ? 00:00:00 /usr/local/php72/bin/php cli.php Event/register
root 1499 1240 0 19:56 pts/1 00:00:00 grep --color=auto Event/register

As you can see. It will show the whole command path for us to execute PHP script. There is no way to pretend to be a special name, or an elegant name.

Consult relevant information. In fact, PHP already supports this operation.

1. proctitle Extension Implementation

Prior to PHP version 5.5. 0, it was only implemented through proctitle extensions. Download address:

About installing this PHP C extension. The instructions will not be shown here. There are many tutorials on PHP C extensions.

After the proctitle extension is installed. Custom process names are implemented through the setproctitle method provided by this extension.



At this point, we command to run the script:

$php process.php

The script will sleep for 30 seconds. At this time, we open another terminal to check the name of the process. You will find that the extension name has been changed to "NewProcess".

Since this extension has not been updated for 7 years. Therefore, it is not recommended to use.

2. Implementation of the cli_set_process_title method

Beginning with PHP 5.5. 0, PHP has built-in cli_set_process_title methods to resolve this function of reset process names. All I can say is, it's so sweet.

It is also easy to use.



After executing the script, let's still not open a command terminal to view:

[root@localhost public]# ps -ef|grep NewProcess
root 10489 1240 0 09:49 pts/1 00:00:00 NewProcess
root 10496 1221 0 09:50 pts/0 00:00:00 grep --color=auto NewProcess

We can see. It's already in effect.

It is so simple. We can grace the process name later. It can also be used to disguise and hide yourself. In a word, you can do whatever you want with this magical name.


Related articles: