8

I am facing one issue regarding killing a Linux process from my php code. I am running a Scrapy tool from my php code using the proc_open() function in the background.

It works fine, but now I want to kill this process using its process id. To do that I'm using exec("sudo kill -9 $pid"); where $pid is the process id which I'm getting from my php code.

The problem is this process is running on behalf of the apache user. I thought there might be some permissions issue, so I added apache user to the sudoers file like this apache ALL=(ALL) NOPASSWD:ALL but I'm still not able to kill it. Somehow, the same kill command works from my putty console.

My code is on an Amazon EC2 instance.

My question is, how can I kill that process identified by a pid from php?

Ethan
  • 4,295
  • 4
  • 25
  • 44
kishan
  • 189
  • 1
  • 4
  • 14

3 Answers3

28

Never, ever, give apache sudo permissions!

Use exec("kill -9 $pid"); - your apache process started it, it can kill it :)

Sudipta Chatterjee
  • 4,592
  • 1
  • 27
  • 30
  • 2
    i couldn't do it with exec so i just needed to use shell_exec but anyway thanks it helped me a lot :) – virusivv Dec 21 '15 at 00:29
  • 2
    Don't use `exec()` for this, use `posix_kill()` instead. Also, it's bad practice to routinely use kill -9 as it forces the process to die instantly without cleanup (see other answer). Instead, reserve kill -9 for when a process won't die. with kill -15 or kill -1 (SIGHUP). – Brian C Jan 27 '20 at 02:42
10

Try posix_kill:

bool posix_kill ( int $pid , int $sig )

Send the signal sig to the process with the process identifier pid.

Community
  • 1
  • 1
0

You can use exec with sudo privileges for skill that is more safer check out kill users processes in linux with php

Thanks & Regards,
Alok Thaker

Community
  • 1
  • 1
linux_fanatic
  • 4,767
  • 3
  • 19
  • 20