我需要計算通過標準輸入發送到子進程的字節數,以及子進程寫入標準輸出和標準錯誤的字節數。子進程調用execvp,所以我無法從進程內部監視這些統計信息。我目前的策略是創建3個額外的子進程,每個子進程通過管道監視每個std流(或者在stdin的情況下,從stdin讀取)。在標準輸入,標準輸出和標準錯誤中的監視器字節C
這種策略看起來真的很虛弱,我做了一些奇怪的事情,使得監視stdout/err的進程無法從管道各自的末端讀取(並使它們無限期掛起)。下面的代碼。
這將創建三個輔助子進程,並應讓他們算統計:
void controles(struct fds *des)
{
int ex[2];
int err[2];
int n_in = 0;
int c_in;
int n_ex = 0;
int c_ex;
int n_err = 0;
int c_err;
pipe(ex);
pipe(err);
/*has two fields, for the write end of the stdout pipe and the stderr pipe. */
des->err = err[1];
des->ex = ex[1];
switch (fork()) {
case 0: /*stdin */
while (read(0, &c_in, 1) == 1)
n_in++;
if (n_in > 0)
printf("%d bytes to stdin\n", n_in);
exit(n_in);
default:
break;
}
switch (fork()) {
case 0: /*stdout */
close(ex[1]);
/*pretty sure this is wrong */
while (read(ex[0], &c_ex, 1) == 1) {
n_ex++;
write(1, &c_ex, 1);
}
if (n_ex > 0)
printf("%d bytes to stdout\n", n_ex);
close(ex[0]);
exit(n_ex);
default:
close(ex[0]);
}
switch (fork()) {
case 0: /*error */
close(err[1]);
/*also probably have a problem here */
while (read(err[0], &c_err, 1) == 1) {
n_err++;
write(2, &c_err, 1);
}
if (n_err > 0)
printf("%d bytes to stderr\n", n_err);
close(err[0]);
exit(n_err);
default:
close(err[0]);
}
}
,這是一個代碼片段(子進程中),其從FDS結構設置兩個FD的以便子進程應該寫入管道而不是stdin/stderr。
dup2(des.ex, 1);
dup2(des.err, 2);
close(des.ex); close(des.err); /*Is this right?*/
execvp(opts->exec, opts->options); /*sure this is working fine*/
我迷路了,任何幫助,將不勝感激。
1.你可以在一個進程中提供所有三個管道(根據你希望結果如何傳遞,它甚至可以是一個shell腳本)2.如果進程掛起,這可能在工作中緩衝;確保管道沒有緩衝(至少對於輸入管道) – sehe 2011-05-26 21:38:38