【发布时间】:2016-08-22 06:03:50
【问题描述】:
所以,我想在 C 中执行以下命令行:
ps -eo user,pid,ppid 2> log.txt | grep user 2>>log.txt | sort -nk2 > out.txt
但我不确定,代码怎么会是…… 我很困惑如何将命令的输出写入文件,正确和错误输出......
另外,我不知道应该如何构建管道以及当 pid == -1 或 pid > 0 时该怎么做...
我的代码如下:
int main(){
int fd0[2], fd1[2], pid0, pid1;
pipe(fd0);
pid0 = fork();
if (pid == 0){
close(1);
dup(fd0[0]);
fd_file= open(“./out.txt”, O_WRONLY | O_CREAT | O_TRUNC, 00600);
execl("sort","-nk2",">fd_file");
pipe(fd1);
pid1 = fork();
if (pid1 == 0){
close(1);
dup(fd1[0]);
...?
}
}
else if (pid == -1){
perror("ERROR AT SORT!\n");
exit(1);
}
return 0;
}
【问题讨论】:
-
为了处理错误,最好的办法可能是退出(在
main()或exit()中返回)。 -
不要在传递给
perror的字符串末尾添加换行符。perror将打印您的字符串,后跟:,如果冒号从新行开始,这看起来很奇怪。 -
execl之后的下一行只有在execl失败时才会执行。 -
execl中的">fd_file"将作为参数传递给sort,它不会进行重定向 - 这是由 shell 完成的,并且您没有运行 shell。