(; ̄ェ ̄)。 2022-11-26 23:46 采纳率: 66.7%
浏览 13
已结题

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

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

  • 写回答

3条回答 默认 最新

  • 千册 Linux领域新星创作者 2022-11-27 10:19
    关注

    首先写一个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:~$
    
    
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 12月5日
  • 已采纳回答 11月27日
  • 创建了问题 11月26日

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私