1

I'm working on a feature which requires writing a single log file(identified by its path) in multiple processes. Previously, each process used to call printf to stream the log on terminal(standard output). Now I need to change the output destination to a file. So I tried using freopen to redirect the stdout to the file in each process.

freopen(file_path, "a", stdout); //

But it seems it doesn't work well. Some log is missing. What's the common practice to achieve this ?

B.T.W In our requirement, the user should be allowed to switch logging destination between file and standard output, so the first argument "file_path" could be tty when switched back to terminal. Is that OK to call freopen(tty, "a", stdout)?

4

3 に答える 3

2

多くのオプションがあります:

1) 最も単純なアプローチは、すべてのプロセスが同じログに個別に書き込むことです。もちろん問題は、2 つのプロセスが同時に異なるメッセージを書き込んだ場合、ファイルが混乱することです。

2) 代わりに、プロセスにメッセージを 1 つの「マスター ロガー」に送信させることができます。これにより、受信した順序で一度に 1 つずつメッセージが出力されます。「マスターロガー」はソケットを使用する場合があります。すべてのプロセスが同じホスト上にある場合は、代わりにメッセージ キューまたは名前付きパイプを使用できます。

3) さらに単純に、システム全体のセマフォを使用して、一度に 1 つのメッセージのみが書き込まれるようにすることができます。

4) さらに別のアプローチとして、 log4jsyslog-ngなどのオープンソースのロガーを使用することもできます

于 2013-04-15T15:56:39.517 に答える
0

出力を、たとえば output using というファイル ハンドルにパイプしますfprintf。ファイルハンドルは単なるポインタなので、output = stdoutorを設定するだけoutput = yourFileです。次にfprintf(output, "sometext")、その時点でそのハンドルが設定されている場所にすべてが行きます。ユーザー入力に基づいてその場で出力を動的にリダイレクトする機能を使用することもできます。

于 2013-04-15T16:12:01.857 に答える