0
我有一个关于ptrace和管道的练习。以下代码是整个程序的一部分。 管道是在主要部分和this_trace.s_out为1之前制作的。主要的父亲创建孩子,并且这个孩子为自己的孩子制作标准输出。当程序运行ls时,它在屏幕上打印并且不写入文件。哪里不对?用管道和叉子重定向标准输出C
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);
}
对不起,我的英文不好。
谢谢。经过很多时间后,有些事情很难看清。一些变量用于其他重定向。这么多进程的原因是给我们练习的教授 – pagratios 2013-04-24 01:00:30
我刚刚完成了你的修改,一切正常。 再次 – pagratios 2013-04-24 01:14:47
感谢您对于标准输入我这样做,但该计划永远不会结束,而不CTRL-C 做 { \t如果((length0 =读(FD0,BUF0,BUFFSIZE))== -1) \t { \t \t perror(“Read for stdin redirection”); \t \t exit(1); \t} \t write(p_in [WRITE],buf0,length0); } while(length0> 0); – pagratios 2013-04-24 01:41:54