I have two commands cmd1 and cmd2 and I have to execute cmd1 in a child, redirect the output to another child and then execute cmd2 with the output of cmd1 as an argument. Then I have to redirect the output to a remote client (telnet) connected with a socket. I can't figure out the problem but my solution doesn't redirect cmd1 output to cmd2.
if(fork() == 0)
{
//Process to compute cmd1
char *arg[2];
arg[0] = cmd1;
arg[1] = NULL;
dup(piped[1]);
close(piped[0]);
close(piped[1]);
execvp(cmd1,arg);
}
if(fork() == 0)
{
//Process to compute cmd2
dup2(newsockfd,STDOUT_FILENO);
dup2(newsockfd,STDERR_FILENO);
char *arg[2];
arg[0] = cmd2;
arg[1] = NULL;
dup(piped[0]);
close(piped[0]);
close(piped[1]);
execvp(cmd2,arg);
}
Just to be clear. The problem is not in socket inizilization or pipe that's why I reported only the main part
According to my understanding, what you want would be like something below
if(fork() == 0)
{
//Process to compute cmd1
char *arg[2];
arg[0] = cmd1;
arg[1] = NULL;
dup2(piped[1],STDOUT_FILENO); //Redirect stdout to pipe's write end
dup2(piped[1],STDERR_FILENO); //Redirect stderr to pipe's write end
close(piped[0]);
close(piped[1]);
close(newsockfd);
execvp(cmd1,arg);
}
if(fork() == 0)
{
//Process to compute cmd2
char *arg[2];
arg[0] = cmd2;
arg[1] = NULL;
dup2(piped[0],STDIN_FILENO); //Redirect pipe's read end to stdin
dup2(newsockfd,STDOUT_FILENO); //Redirect stdout to socket
dup2(newsockfd,STDERR_FILENO); //Redirect stderr to socket
close(piped[0]);
close(piped[1]);
close(newsockfd);
execvp(cmd2,arg);
}
close(piped[0]);
close(piped[1]);
close(newsockfd);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.