首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Linux上的C中,popen/system到"ps all> file"会将所有行截断为80个字符

Linux上的C中,popensystem函数用于执行外部命令,将输出重定向到文件。在Linux上使用popensystem执行ps命令,并将输出重定向到文件,可以获取Linux服务器上所有进程的信息。

具体实现代码如下:

代码语言:c
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    char cmd[1024];

    // 打开目录
    dir = opendir("/proc");
    if (dir == NULL) {
        perror("Error: Could not open /proc directory");
        return 1;
    }

    // 遍历目录,读取每个进程的信息
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            // 获取进程ID
            pid_t pid = atoi(entry->d_name);

            // 打开进程文件
            FILE *fp = fopen(entry->d_name, "r");
            if (fp == NULL) {
                perror("Error: Could not open process file");
                continue;
            }

            // 读取进程的详细信息
            while (fgets(cmd, sizeof(cmd), fp) != NULL) {
                // 过滤出进程名称和进程状态
                if (strncmp(cmd, "Name:", 5) == 0) {
                    cmd[strlen(cmd) - 1] = '\0';
                    printf("Process Name: %s\n", cmd);
                } else if (strncmp(cmd, "State:", 6) == 0) {
                    cmd[strlen(cmd) - 1] = '\0';
                    printf("Process State: %s\n", cmd);
                }
            }

            // 关闭进程文件
            fclose(fp);
        }
    }

    // 关闭目录
    closedir(dir);
    return 0;
}

在上面的代码中,我们使用opendir函数打开/proc目录,然后使用readdir函数遍历目录,读取每个进程的信息。如果读取到的进程信息是目录,则使用atoi函数获取进程ID,并使用fopen函数打开进程文件,读取进程的详细信息。最后使用fclose函数关闭进程文件,并使用closedir函数关闭目录。

在上面的代码中,我们过滤出进程名称和进程状态,并输出到控制台上。

可以通过修改命令行,将需要过滤的进程信息提取出来,并保存到文件中使用。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券