2013-04-23 76 views
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); 


} 

對不起,我的英文不好。

回答

1

不清楚爲什麼你有這麼多的過程。你有一個問題:

if (fd1 = open(this_trace.out_name,O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1) 

這就賦予0或1至fd1,不管文件描述符的打開。它應該是:

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()返回,則失敗。

您顯示未使用的變量buf0buf2(和相應的length0length2)。

+0

謝謝。經過很多時間後,有些事情很難看清。一些變量用於其他重定向。這麼多進程的原因是給我們練習的教授 – pagratios 2013-04-24 01:00:30

+0

我剛剛完成了你的修改,一切正常。 再次 – pagratios 2013-04-24 01:14:47

+0

感謝您對於標準輸入我這樣做,但該計劃永遠不會結束,而不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

相關問題