Skip to content

Commit

Permalink
cleanup(userspace/libscap): avoid the usage of non-portable (glibc sp…
Browse files Browse the repository at this point in the history
…ecific) `__gnu_cxx::stdio_filebuf`.

Signed-off-by: Federico Di Pierro <[email protected]>
  • Loading branch information
FedeDP committed Sep 11, 2024
1 parent 215db2d commit 28ba006
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions userspace/libscap/engine/gvisor/runsc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ limitations under the License.
*/

#include <unistd.h>
#include <sys/wait.h>
#include <ext/stdio_filebuf.h>
#include <iostream>
#include <fstream>
#include <string>

#include <libscap/engine/gvisor/gvisor.h>
Expand All @@ -30,36 +26,37 @@ namespace runsc {

result runsc(char *argv[]) {
result res;
int pipefds[2];

int ret = pipe(pipefds);
if(ret) {
return res;
std::string full_command;
int i = 0;
while(true) {
if(argv[i] == nullptr) {
break;
}
full_command.append(argv[i]);
full_command.append(" ");
i++;
}

pid_t pid = vfork();
if(pid > 0) {
int status;

close(pipefds[1]);
wait(&status);
FILE *cmd_out = popen(full_command.c_str(), "r");
if(cmd_out == nullptr) {
res.error = -errno;
} else {
char *out = nullptr;
size_t len = 0;
ssize_t readbytes;
while((readbytes = getline(&out, &len, cmd_out)) >= 0) {
// getline() returns string comprehensive of newline char;
// drop it if found.
if(out[readbytes - 1] == '\n') {
out[readbytes - 1] = '\0';
}
res.output.emplace_back(out);
}
free(out);
int status = pclose(cmd_out);
if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
res.error = status;
return res;
}

__gnu_cxx::stdio_filebuf<char> filebuf(pipefds[0], std::ios::in);
std::string line;
std::istream is(&filebuf);

while(std::getline(is, line)) {
res.output.emplace_back(std::string(line));
}
} else {
close(pipefds[0]);
dup2(pipefds[1], STDOUT_FILENO);
execvp("runsc", argv);
exit(1);
}

return res;
Expand Down

0 comments on commit 28ba006

Please sign in to comment.