gpt4 book ai didi

c - 输出文件描述符重定向到管道的进程正在屏幕而不是管道上写入

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:01 25 4
gpt4 key购买 nike

所以这是我的代码,socket、nameExecutable和commandLineArgs都是函数接收的参数。

我的问题是新进程没有写入其管道,而是写入终端。

此代码的目标是让子进程将其输出写入父进程,然后父进程通过套接字发送它,当通过套接字接收到内容时,父进程将其发送给子进程进行处理。

char bufferWriteToClient[BUFFER_WRITE_SIZE],bufferReadFromClient[BUFFER_READ_SIZE];
pid_t pid;
fd_set readSet;
FD_ZERO(&readSet);
struct timeval timeVal;
int pipeDad[2],pipeSon[2],returnState;
if (pipe(pipeDad) < 0)
return -1;
if (pipe(pipeSon) < 0){
close(pipeDad[0]);
close(pipeDad[1]);
return -1;
} // End of pipe initialization


switch ((pid = fork())){
case -1:
close(pipeDad[0]);
close(pipeDad[1]);
close(pipeSon[0]);
close(pipeSon[1]);
return -1;
case 0:
// Duplicate new process stdin and stdout to be the parents pipe received end and childs pipe writing end

dup2(STDIN_FILENO,pipeDad[0]);
dup2(STDOUT_FILENO,pipeSon[1]);

// Close the ends we don't need
close(pipeSon[0]);
close(pipeDad[1]);
execv(nameExecutable,commandLineArgs);
break;
default:
// Close the ends attributed to the child process
close(pipeDad[0]);
close(pipeSon[1]);
// --------------------------------
while (!waitpid(pid,&returnState,WNOHANG)){
int retValSelect;
FD_SET(pipeSon[0],&readSet);
FD_SET(socket,&readSet);
timeVal.tv_sec = 3;
timeVal.tv_usec = 0;
retValSelect = select(pipeSon[0] > socket ? pipeSon[0]+1:socket+1,&readSet,NULL,NULL,&timeVal);
if (retValSelect == -1){
return -1;
}
if (FD_ISSET(pipeSon[0],&readSet)){
int receivedBytes = readUpToData(socket,bufferWriteToClient,sizeof(bufferWriteToClient)-1);
if (receivedBytes == -1)
return -1;
if (bufferWriteToClient[receivedBytes] != '\0')
bufferWriteToClient[receivedBytes+1] = '\0';
sendData(socket,bufferWriteToClient,strlen(bufferWriteToClient)+1);
}
if (FD_ISSET(socket,&readSet)){
int receivedBytes = readUpToData(socket,bufferReadFromClient,sizeof(bufferReadFromClient)-1);
if (receivedBytes == -1)
return -1;
if (bufferReadFromClient[receivedBytes] != '\0')
bufferReadFromClient[receivedBytes+1] = '\0';
sendData(pipeDad[1],bufferReadFromClient,strlen(bufferReadFromClient)+1);
}
}
break;
}

所以在我进入 switch 中的默认情况之前,子进程已经写入终端,谁能告诉我我做错了什么?

最佳答案

看起来你颠倒了 dup2() 的参数。来自 dup(2) 手册页:

NAME dup, dup2, dup3 - duplicate a file descriptor

SYNOPSIS

   #include <unistd.h>

int dup(int oldfd);
int dup2(int oldfd, int newfd);

关于c - 输出文件描述符重定向到管道的进程正在屏幕而不是管道上写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com