c语言执行命令

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;
}

  

posted on 2020-02-07 15:41  luckygxf  阅读(1335)  评论(0编辑  收藏  举报

导航