Streaming execvp output via socket
Question
I know this question has been asked a billion times, but all the solutions are not working for me. I need to stream the stdout
of an execvp
via a socket to a client. The relevant client code is this
static void execute_cmd(int fd, char *cmd, char **params) {
pid_t cid;
size_t i = 0, c = 0;
cid = fork();
if(cid == 0) {
close(STDOUT_FILENO);
dup2(fd, STDOUT_FILENO);
if(execvp(cmd, params) < 0) {
fprintf(stderr, "Could not execute \"%s\": %d\n", cmd, errno);
exit(1);
}
} else {
close(fd);
waitpid(cid, NULL, 0);
exit(1);
}
}
I have tried to copy the answer on this question. However, I get nothing back when I try this code:
int sockfd = serverConnect();
write(sockfd, "echo math", 11);
n = read(sockfd, buffer, 1023);
printf("Got %d bytes\n", n);
printf("%s\n", buffer);
close(sockfd);
I triple checked that the connection is established correctly. When I replace execute_cmd
with a simple write
, the client correctly prints the answer. But nothing happens when I execute the code above, I get no bytes back. I have removed the dup2
call and got no output from the execvp
call either.
Getting quite desperate here, tried pipe
and whatever I could find. Where did I go wrong? The command itself is ok, too, works on the shell, and the execvp
call does not throw an error.
Solution
Turns out the code above is correct. The problem was an incorrect use of an earlier strtok
that resulted in a silent crash of strdup
. The fork
above was simply never executed, and all my tests were above the strtok
line. Only after putting printf
s into every line of the code I could find the problem.
Frankly, I feel stupid.