cgi_script read and write on a string

This commit is contained in:
hugogogo
2022-08-07 22:33:39 +02:00
parent 7ecfc22c7b
commit 63365a9067

View File

@@ -68,22 +68,49 @@ char** Webserv::_set_env(Client *client)
void Webserv::_exec_script(Client *client, char **env)
{
int save_stdout;
char * const * nll = NULL;
#define RD 0
#define WR 1
#define BUF_SIZE 10
// save STDOUT
save_stdout = dup(STDOUT_FILENO);
// inside child process
char buf[BUF_SIZE];
int fd_in[2];
int fd_out[2];
char * const * nll = NULL;
std::string response;
std::string body = client->get_rq_body();
pipe(fd_in);
pipe(fd_out);
if (fork() == 0)
{
dup2(client->get_cl_fd(), STDOUT_FILENO);
{
close(fd_in[WR]);
close(fd_out[RD]);
dup2(fd_in[RD], STDIN_FILENO);
dup2(fd_out[WR], STDOUT_FILENO);
execve(client->get_rq_script_path().c_str(), nll, env);
std::cerr << "execve crashed\n";
}
// inside parent process
else
{
close(fd_in[RD]);
close(fd_out[WR]);
// write to stdin of child programm
write(fd_in[WR], body.c_str(), body.size());
close(fd_in[WR]);
waitpid(-1, NULL, 0);
// restore stdout
dup2(save_stdout, STDOUT_FILENO);
// read stdout of child programm
memset(buf, '\0', BUF_SIZE);
while (read(fd_out[RD], buf, BUF_SIZE) > 0)
{
response += buf;
memset(buf, '\0', BUF_SIZE);
}
}
if (response.empty())
response += "Status: 500\r\n\r\n";
// TODO: see how this must be handled
client->response += response;
}
void Webserv::_construct_client(Client *client)