我有一个关于 ptrace 和管道的练习。以下代码是整个程序的一部分。管道在主要部分之前制作,this_trace.s_out 为 1。主要父亲创建孩子,这个孩子为标准输出创建自己的孩子。当程序运行 ls 然后它在屏幕上打印并且不写入文件。怎么了?
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);
}
对不起,我的英语不好。