[英]Redirect stdout with pipes and fork in C
我有關於ptrace和管道的練習。 以下代碼是整個程序的一部分。 在主要部分之前制作管道,this_trace.s_out為1。主要父親創建一個孩子,這個孩子為stdout制作了自己的孩子。 當程序運行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);
}
對不起,我的英語不好。
目前尚不清楚為什么會有這么多流程。 您有以下問題:
if (fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
這將為fd1
分配0或1,而與打開的文件描述符無關。 它應該是:
if ((fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
使用dup2()
(或dup()
)將文件描述符重定向到標准通道后,應關閉原始文件描述符。 因此,在dup2(p_out[WRITE], 1);
您需要close(p_out[WRITE]);
。
您應該從execl()
檢測到故障並進行處理; 如果execl()
返回,則失敗。
您將顯示未使用的變量buf0
和buf2
(以及相應的length0
和length2
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.