---
title: "判断在linux以命令行执行的文件是否还在执行"
author: "conkeyn"
date: "2010-06-03T10:37:55Z"
tags: []
categories: ["编程语言"]
slug: "linux"
draft: false
lastmod: "2010-06-03T10:37:55Z"
id: 682762
url: "https://conkeyn.iteye.com/blog/682762"
---

```
// 取得当前程序进程，用来判断是否可以执行
$gather_in_pro = shell_exec('ps -ef | grep "' . basename(__FILE__) . '"|grep -v grep | awk \'{print $2}\'');

// 判断进程中有几个本程序，如果只有一个说明是本程序的主程序，
// 如果超过一个则说明仍有本程序的子进程在运行
// 计划任务执行时会产生两个进程：
//         /bin/sh -c php your_phpfile.php
//         php your_phpfile.php
// 所以判断条件（当前程序进程数）应大于 2
if (count(explode("\n", trim($gather_in_pro))) > 2)
{
    // 如果进程不为空则说明当前正在执行，给予提示并退出程序
    echo "\n采集、分析程序正在运行！\n";
    echo shell_exec('ps -ef | grep "' . basename(__FILE__) . '"|grep -v grep') . "\n";
    exit();
}
```