我需要將stdout
和stderr
的子進程複製到多個文件。
據我所知,我可以使用tee()
,但我還沒有找到這方面的例子。 現在,只能將所有內容打印到stdout和stderr。 如何做到這一點?複製stdout和stderr從fork進程到文件
pid_t childId = fork();
switch(childId){
case -1:
perror("fork() error!\n");
return;
case 0:
mysignal(SIGTTOU, SIG_DFL);
mysignal(SIGTTIN, SIG_DFL);
mysignal(SIGCHLD, SIG_DFL);
if(!background)
tcsetpgrp(cterm, getpid());
setpgid(0, 0);
if (isWriter) close(pipefd[0]);
if (isReader!=-1) {
close(0);
dup(oldChannelOut);
}
if(isWriter){
close(1);
dup(pipefd[1]);
}
//exec, if program is in current directory
execv(commandArgv[0], commandArgv);
int i = 0;
char buf[_POSIX_MAX_PATH];
while(path[i] != NULL){
buf[0] = '\0';
strcat(buf, path[i]);
if(path[i][ strlen(path[i])-1 ] != '/'){
buf[strlen(path[i])] = '/';
buf[strlen(path[i])+1] = '\0';
}
strcat(buf, commandArgv[0]);
execv(buf, commandArgv);
++i;
}
fprintf(stderr,"\"%s\": command not found\n",commandArgv[0]);
exit(1);
UPD:試圖修改,不工作後。問題在哪裏?
fdout=open("1", O_APPEND | O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
fderr=open("2",O_APPEND | O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
...
case 0:
if (isReader!=-1) {
close(0);
dup(oldChannelOut);
}
dup2(fdout, 1);
dup2(fderr, 2);
close(fdout);
close(fderr);
exec....
default:
{
if(background) {
addJob(&jobListStartB,childId,commandArgv,BACKGROUND);
if (oldChannelOut != -1){
close(oldChannelOut);
oldChannelOut = -1;
}
}
else if(!background){
if (oldChannelOut != -1){
close(oldChannelOut);
oldChannelOut = -1;
}
}
因此,派生進程的輸出和錯誤將被寫入到輸出和錯誤,以及兩個文件,對吧? – Deduplicator 2014-12-04 13:14:56
它們必須是DUPLICATE到兩個文件,而不是隻寫。 – 2014-12-04 13:24:38
你是什麼意思? – Deduplicator 2014-12-04 13:35:23