首页 > 编程语言 > 详细

c语言执行命令

时间:2020-02-07 16:20:34      阅读:52      评论:0      收藏:0      [点我收藏+]

1. system函数

2. popen函数

#include <stdio.h>
#include <stdlib.h>

#define BUFFSIZE 1024

typedef struct info {
    char pid[20];
    char user[20];
} topInfo;

int getServerInfo(topInfo topInfos[]);

int main() {
    int i = 0;
//    system("ls /");
    topInfo topInfos[20];
    int len = getServerInfo(topInfos);
    for (; i < len; i++) {
        printf("pid :%s, user: %s\n", topInfos[i].pid, topInfos[i].user);
    }

    return 0;
}

int getServerInfo(topInfo topInfos[]) {
    char cmd[] = "top -n 1";
    FILE *file = popen(cmd, "r");
    char buff[BUFFSIZE];

    if (!file) {
        fprintf(stderr, "popen top fail");
        exit(1);
    }
    int i = 0, k = 0;
    for (; fgets(buff, sizeof(buff), file) != NULL; k++) {
//        printf("%s", buff);
        if (k < 12)
            continue;
        sscanf(buff, "%s %s", topInfos[i].pid, topInfos[i].user);
        i++;
        break;
    }
    pclose(file);
    return i;
}

  

c语言执行命令

原文:https://www.cnblogs.com/luckygxf/p/12273266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!