Redirect stdout and stderr to a socket for a distributed shell program

I created a distributed shell program with client and server. The client sends a command request to the server, and the server runs this command locally and should output the results of this command to the client. I find it hard to figure out how to redirect stdout / stderr to a client. I use execvp to execute the command.

Think I might have to use dup2? But I can’t figure out how to use it properly. Any help?

+5
source share
1 answer

You just need to use the dup2()duplicate file descriptor socket in the file descriptors stderr and stdout. This is almost the same as pipe redirection.

cpid = fork();
if (cpid == 0) {
  dup2(sockfd, STDOUT_FILENO);
  dup2(sockfd, STDERR_FILENO);
  execvp(...);
  /*... etc. etc. */
+7
source

All Articles