2016-04-19 94 views
2

我寫了一個程序,打印一條消息,等待用戶輸入並再次打印消息。下面的簡單例子說明了這一點。該程序與'prog |一起啓動tr'a-z「'A-Z'。只有最後一張照片應該由'tr'a-z''A-Z'處理。如何重定向一個殼創建的管道

int main() 
{ 
    char name[99]; 
    printf ("Your name: "); 
    scanf ("%98s", name); 
    printf ("Your name is: %s\n", name); 

    return 0; 
} 

我已經嘗試了很多管道,dup,dup2,但沒有任何工作到目前爲止。有沒有人有一個想法如何解決我的問題?

回答

1

如果你想使用這個命令來啓動你的程序,只有這樣,才能做你想要將在標準錯誤消息打印什麼:

fprintf (stderr, "Your name: \n"); 
+0

謝謝您的回答。我想過stderr,但我希望我可以避免誤用stderr。 –

+0

@NickBendner爲什麼你試圖做「重定向殼創建的管道」? – jdarthenay

+0

在某些情況下,我的編程請求用戶輸入。在此之前,它會打印一條消息,說明爲什麼需要輸入以及它期望的輸入類型。除非用戶用管道開始編程,否則一切運作良好。如果用戶這樣做,則不會打印該消息,因爲標準輸出會被緩衝並重定向到管道。用戶只會看到一個提示,但他不知道爲什麼,他現在應該做什麼。我的想法是暫停管道,打印消息,獲取用戶輸入,然後恢復管道。 –

0

一些研究之後,我發現how to check if stdout is directed to a terminalhow to write to terminal甚至如果沒有處理它。

所以,你可以按照以下步驟:

#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <unistd.h> 

int print_to_terminal(const char *message) 
{ 
    FILE *termout; 

    if (isatty(STDOUT_FILENO)) 
    { 
     termout = stdout; 
    } 
    else 
    { 
     termout = fopen("/dev/tty", "w"); 
     if (termout == NULL) 
     { 
      perror("open"); 
      return EOF; 
     } 
    } 

    int result = fprintf(termout, "%s\n", message); 

    if (termout != stdout) 
    { 
     fclose(termout); 
    } 

    return result; 
} 

int main() 
{ 
    printf("Start of program.\n"); 
    print_to_terminal("Don't worry, be happy."); 
    printf("End of program.\n"); 

    return 0; 
} 

的消息應該在即使兩個輸出和錯誤被定向到一個文件當前終端打印。

+0

謝謝。我會嘗試。 –

0

使用尾巴:http://linux.die.net/man/1/tail

prog | tail -n 1 | tr 'a-z' 'A-Z' 
+0

感謝您的回答,但用戶決定他如何開始編程。 tr'a-z''A-Z'只是一個例子,目的是爲了說明編程無法在管道中正常工作。 –