所以,我有这个命令行,我想用C:
执行ps -eo user,pid,ppid 2> log.txt | grep user 2>>log.txt | sort -nk2 > out.txt
我需要弄清楚我是如何制作代码的...... fd 我的理解是我有父亲ps ...哪个需要将输出重定向为grep的输入,并且还需要将输出错误输出到log.txt ......
与grep相同...必须将输出重定向到排序,并且必须将错误保存在log.txt中。
我只是将排序输出到文件......
这样的事情:
FATHER(ps) SON(grep) SON-SON? (sort)
0->must be closed ----> 0 ----> 0
/ /
1 ---------------/ 1 --------/ 1 -->out.txt
2 ---> log.txt 2 ---> log.txt 2 -->nowhere?
但我不知道这是如何编码的...... 我很感激你的帮助。
答案 0 :(得分:0)
您可以使用sh -c
(How do I execute a Shell built-in command with a C function?)
管道也可以直接使用popen()
以下程序示例显示如何将ps -A
命令的输出传递给grep init
命令:ps -A | grep init
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
FILE *ps_pipe;
FILE *grep_pipe;
int bytes_read;
int nbytes = 100;
char *my_string;
/* Open our two pipes */
ps_pipe = popen ("ps -A", "r");
grep_pipe = popen ("grep init", "w");
/* Check that pipes are non-null, therefore open */
if ((!ps_pipe) || (!grep_pipe))
{
fprintf (stderr,
"One or both pipes failed.\n");
return EXIT_FAILURE;
}
/* Read from ps_pipe until two newlines */
my_string = (char *) malloc (nbytes + 1);
bytes_read = getdelim (&my_string, &nbytes, "\n\n", ps_pipe);
/* Close ps_pipe, checking for errors */
if (pclose (ps_pipe) != 0)
{
fprintf (stderr,
"Could not run 'ps', or other error.\n");
}
/* Send output of 'ps -A' to 'grep init', with two newlines */
fprintf (grep_pipe, "%s\n\n", my_string);
/* Close grep_pipe, checking for errors */
if (pclose (grep_pipe) != 0)
{
fprintf (stderr,
"Could not run 'grep', or other error.\n");
}
/* Exit! */
return 0;
}
来源:http://crasseux.com/books/ctutorial/Programming-with-pipes.html
否则使用命名管道(https://en.wikipedia.org/wiki/Named_pipe) http://www.cs.fredonia.edu/zubairi/s2k2/csit431/more_pipes.html
另请参阅此C program to perform a pipe on three commands(使用fork()
)