我的朋友有以下任务,任何人都可以指导如何在“C”中执行此操作,只需指导即可。
编写程序将所有进程列表存储到文件中,并使用UID对所有进程进行排序。
例如:
./a.out processidlist.txt
必须将信息保存到processidlist.txt。
在此processidlist.txt中,它必须使用UID对进程进行排序。
他尝试了下面的
ps –A –o UID > outputfile
由于
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp1, *fp2;
FILE *fp;
int status;
char path[1035];
fp1 = fopen( argv[1], "w" );
if ( ! fp1 )
{
printf("Error opening file %s\n", argv[1]);
}
/* Open the command for reading. */
fp = popen("ps -Af | sort -k1", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
fputs( path, fp1 );
}
/* close */
pclose(fp);
fclose(fp1);
return 0;
}
答案 0 :(得分:2)
这些行上的某些内容应该有效
system("ps -Af | sort -k1");
A indicates all processes
f generates full listing
k denotes sort by column
1 denotes first column which is UID of the processes
如果你不想要恼人的标题
UID PID PPID C STIME TTY TIME CMD
以及您的流程列表,然后使用sed
删除ps
输出的第一行
system("ps -Af | sed "1 d" | sort -k1");
答案 1 :(得分:1)
您需要提供问题的上下文。即试图教你的家庭作业是什么?
您是否正在学习检查所有流程的特定API? (所以人们可以明智地假设你应该使用它。)
如果没有,像Pavan的system()
电话这样的话可能有效。 (但是,如果它被一行shell脚本解决,你为什么要求编写一个C程序?)
另外:关于问题的评论中的“ps” - 它具体说是写一个程序,为什么“他”认为ps命令行是否足够?