[英]Redirect stdout with pipes and fork in C
I have an exercise about ptrace and pipes. 我有关于ptrace和管道的练习。 The following code is a part from whole program.
以下代码是整个程序的一部分。 Pipes are made before main part and this_trace.s_out is 1. Main father create child and this child makes his own child for stdout.
在主要部分之前制作管道,this_trace.s_out为1。主要父亲创建一个孩子,这个孩子为stdout制作了自己的孩子。 When program runs ls then it is print on screen and doesn't write in file.
当程序运行ls时,它将在屏幕上打印并且不写入文件。 What is wrong?
怎么了?
if(pid == 0)
{
char buf0[BUFFSIZE], buf1[BUFFSIZE], buf2[BUFFSIZE];
int length0, length1, length2;
if(this_trace.s_out == 1) //For stdout redirection
{
if((pid1=fork()) == -1)
{
perror("fork");
exit(1);
}
if(pid1 == 0) //child for stdout redirect
{//sleep(2);
if(fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
{
perror("create stdout file");
exit(1);
}
close(p_out[WRITE]);
close(p_in[READ]);
close(p_in[WRITE]);
close(p_err[READ]);
close(p_err[WRITE]);
do{
if((length1 = read(p_out[READ],buf1,BUFFSIZE)) == -1)
{
perror("Read for stdout redirection");
exit(1);
}
write(fd1, buf1, length1);
}while(length1 > 0);
close(fd1);
//close(p_out[READ]);
return 0;
//break;
}
else if(pid1 > 0)//child from main father
{
close(p_out[READ]);
close(p_in[READ]);
close(p_in[WRITE]);
close(p_err[READ]);
close(p_err[WRITE]);
dup2(p_out[WRITE], 1);
}
}
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
//execv(argv[1],NULL);
execl("/bin/ls","ls",NULL);
}
Sorry for my bad English. 对不起,我的英语不好。
It is not clear why you have so many processes. 目前尚不清楚为什么会有这么多流程。 You have a problem at:
您有以下问题:
if (fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
This assigns 0 or 1 to fd1
, regardless of the file descriptor opened. 这将为
fd1
分配0或1,而与打开的文件描述符无关。 It should be: 它应该是:
if ((fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
After you use dup2()
(or dup()
) to redirect a file descriptor to a standard channel, you should close the original file descriptor. 使用
dup2()
(或dup()
)将文件描述符重定向到标准通道后,应关闭原始文件描述符。 Thus, after dup2(p_out[WRITE], 1);
因此,在
dup2(p_out[WRITE], 1);
you need close(p_out[WRITE]);
您需要
close(p_out[WRITE]);
. 。
You should detect failure from execl()
and deal with it; 您应该从
execl()
检测到故障并进行处理; if the execl()
returns, it failed. 如果
execl()
返回,则失败。
You show unused variables buf0
and buf2
(and corresponding length0
and length2
). 您将显示未使用的变量
buf0
和buf2
(以及相应的length0
和length2
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.