[英]How can I redirect stdout back to the terminal in a multi process c program?
I'm trying to write ac program that is the equivalent of the linux command ps -aux | sort -r -n -k 5
我正在尝试编写一个相当于linux命令
ps -aux | sort -r -n -k 5
ac程序 ps -aux | sort -r -n -k 5
but I'm not getting any output ps -aux | sort -r -n -k 5
但我没有得到任何输出
Here's my code 这是我的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char ** argv){
int pipes[2];
int r;
r = pipe(pipes);
if (r < 0) {
fprintf(stderr, "pipe failed\n\n"); // stderr is a FILE* variable for the standard error file (terminal)
exit(2);
}
int saved_stdout = dup(1);
int pid = fork();
if(pid > 0){
// Parent
pid = fork();
if(pid > 0){
// Parent
wait(NULL);
}else if (pid == 0){
// Child 1
printf("Child 1\n");
dup2(pipes[1], 1);
close(pipes[0]);
close(pipes[1]);
execlp("/bin/ps", "ps", "-aux", (char*) NULL);
exit(0);
}else{
fprintf(stderr, "FORK FAILED\n\n");
return 1;
}
}else if (pid == 0){
// Child 2
printf("Child 2\n");
dup2(pipes[0], 0);
close(pipes[0]);
close(pipes[1]);
dup2(saved_stdout, 1);
close(saved_stdout);
execlp("/bin/sort", "sort", "-r", "-n", "-k", "5", (char*)NULL);
exit(0);
}else{
fprintf(stderr, "FORK FAILED\n\n");
return 1;
}
wait(NULL);
printf("Exiting parent\n");
}
The output I get is this 我得到的输出就是这个
Child 1
Child 2
Exiting parent
I doesn't actually print the execlp
command, I've tried saving stdout
to variable saved_stdout
which is the solution I found in another answer, but that doesn't seem to work. 我实际上没有打印
execlp
命令,我已经尝试将stdout
保存到变量saved_stdout
,这是我在另一个答案中找到的解决方案,但这似乎不起作用。
How can I redirect stdout back to the terminal? 如何将stdout重定向回终端?
Strange my output with your code is: 我的代码输出奇怪是:
Child 1
Child 2
and the program don't stop. 而且程序不会停止。 Or you sure that your output is valid ?
或者您确定您的输出有效?
Whatever, your problem is that you don't close your pipe in your parents. 无论如何,你的问题是你不要关闭你父母的烟斗。 Just add:
只需添加:
close(pipes[0]);
close(pipes[1]);
In your both parents (before your two call to wait()
). 在你的父母双方(在你的两个叫
wait()
)。
Plus saved_stdout
is useless in your case, because you only change stdout in your child1. 加上
saved_stdout
在你的情况下没用,因为你只更改了saved_stdout
中的stdout。 saved_stdout
and 1
describe the same file in your child2. saved_stdout
和1
描述了saved_stdout
中的相同文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.