Skip to content

Instantly share code, notes, and snippets.

@unix-beard
Created April 21, 2014 12:25
Show Gist options
  • Save unix-beard/11141350 to your computer and use it in GitHub Desktop.
Save unix-beard/11141350 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "lib/testing.h"
/* Execute this while being in a child process */
static void exec_in_child(const char * test_bin, const int * pipe_fd) {
INFO("exec_in_child");
close(pipe_fd[0]); /* Close unused read end */
dup2(pipe_fd[1], 1); /* write to stdout */
INFO("executing");
int i = execvp(test_bin, NULL);
FATAL("Can't execvp %s", test_bin);
exit(1);
}
static int fork_test_case(const char * test_bin) {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
FATAL("Can't pipe");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0) {
FATAL("Failed to fork");
return EXIT_FAILURE;
}
if (pid == 0) {
/************************************
* child process - doesn't return
************************************/
INFO("exec_in_child");
dup2(pipe_fd[1], STDOUT_FILENO); /* write to stdout */
close(pipe_fd[0]);
close(pipe_fd[1]);
INFO("executing");
int i = execvp(test_bin, NULL);
FATAL("Can't execvp %s", test_bin);
exit(1);
} else {
/************************************
* parent process
************************************/
close(pipe_fd[1]); /* Close unused write end */
char buf;
while (read(pipe_fd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
close(pipe_fd[0]);
int status;
INFO("Waiting for child to exit");
pid_t done = wait(&status);
INFO("Child with pid [%d] finished with status [%d]", done, status);
return status;
}
}
static void start_test(const char * test_bin) {
const size_t buf_size = 128;
char buf[buf_size];
snprintf(buf, buf_size, "Testing [%s]", test_bin);
INFO(buf);
if (fork_test_case(test_bin) == 0)
INFO("Success");
else
INFO("Failure");
}
int main(int argc, char * argv[]) {
INFO("Starting tests");
start_test("test-cpp");
DONE("Finished tests!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment