在linux下,如何用C语言执行 ps -ef | grep server > tmp.txt 这种复杂命令。

在linux下,如何用C语言执行 ps -ef | grep server > tmp.txt 这种命令。

首先写一个system的应用函数,search_process函数接收两个参数,我在你的命令的基础上加了 grep -v grep.。意思就是输出结果中,去掉grep命令本身。这样如果只有一个进程,结果中使用wc -l(小写的L)肯定是由一行


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int search_process(char * proc_name,char *dst_file)
{
    int ret;
    int len = strlen(proc_name) + strlen(dst_file) + 100;
    char *buf = (char *)malloc(len);
    if(strlen(proc_name) == 0 || strlen(dst_file) == 0){
        printf("invalid parameter,%s,%s,%p,%p\n",
            proc_name,dst_file,proc_name,dst_file);
        return -1;
    }
    printf("%s %s\n",proc_name,dst_file);
    sprintf(buf,"ps -ef | grep %s | grep -v grep > %s",proc_name,dst_file);
    ret = system(buf);
    printf("system(%s) = %d\n",buf,ret);
    free(buf);
    return ret;
}

int main(int argc,char *argv[])
{
    if(argc < 2){
        while(1){
            sleep(1);
        }
    }
    if(argc == 3)
    search_process(argv[1],argv[2]);
    printf("bye\n");

    return 0;
}

测试结果
编译

csdn@ubuntu:~$ gcc main.c

运行

csdn@ubuntu:~$ ./a.out a.out dst.txt
a.out dst.txt
system(ps -ef | grep a.out | grep -v grep > dst.txt) = 0
bye
csdn@ubuntu:~$ 

查看生成的目标文件

csdn@ubuntu:~$ cat dst.txt
csdn      62473  62227  0 10:15 pts/20   00:00:00 ./a.out a.out dst.txt
csdn@ubuntu:~$ 

从结果中,可以到搜索到了进程,这种方法可以判断进程的唯一性,不重复运行。
如果a.out不加参数,那么它就是一个测试进程可像下面这样使用:

csdn@ubuntu:~$ ./a.out &
[1] 62497
csdn@ubuntu:~$ ./a.out a.out dst.txt
a.out dst.txt
system(ps -ef | grep a.out | grep -v grep > dst.txt) = 0
bye
csdn@ubuntu:~$ cat dst.txt
csdn      62497  62227  0 10:18 pts/20   00:00:00 ./a.out
csdn      62498  62227  0 10:18 pts/20   00:00:00 ./a.out a.out dst.txt
csdn@ubuntu:~$


现在就有两个进程在同时运行了,如果系统检测到这种情况就需要留意了。

回答:可以试试 system(" "); 函数
这篇文章有简单介绍:https://blog.csdn.net/zhaoxiaoqiang10_/article/details/54926162
或者这篇文章:https://blog.csdn.net/buleskycode/article/details/89249183

1、调用system函数
2、调用popen函数
3、调用exec族函数