Skip to content

Instantly share code, notes, and snippets.

@alenstarx
Created December 17, 2017 06:54
Show Gist options
  • Save alenstarx/e1a54dd95b97391a6b9147e41c3d0386 to your computer and use it in GitHub Desktop.
Save alenstarx/e1a54dd95b97391a6b9147e41c3d0386 to your computer and use it in GitHub Desktop.
fork
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
struct process_info {
char* name;
char* path;
char* args;
int out;
int err;
pid_t pid;
};
int fork_process(struct process_info* pinfo) {
if (pinfo->name == NULL || pinfo->path == NULL) {
return -1;
}
int err_fd[2] = {0x00};
int out_fd[2] = {0x00};
if ((pipe(err_fd) < 0) || (pipe(out_fd) < 0)) {
// pipe failed
// TODO
return -2;
}
pid_t pid = fork();
if (pid < 0) {
// TODO
// fork failed
return -3;
} else if(pid == 0) {
// child process
// TODO
close(out_fd[0]);
close(err_fd[0]);
if (out_fd[1] != STDOUT_FILENO) {
if(dup2(err_fd[1], STDOUT_FILENO) != STDOUT_FILENO) {
// dup2 failed
// TODO
}
close(out_fd[1]);
}
if (err_fd[1] != STDERR_FILENO) {
if(dup2(err_fd[1], STDERR_FILENO) != STDERR_FILENO) {
// dup2 failed
// TODO
}
close(err_fd[1]);
}
if(execl(pinfo->path, pinfo->name, pinfo->args, (char*)NULL) < 0) {
// execl failed
// TODO
return -4;
}
return 0;
} else {
// parent process
// TODO
close(out_fd[1]);
close(err_fd[1]);
pinfo->pid = pid;
pinfo->err = err_fd[0];
pinfo->out = out_fd[0];
}
return 0;
}
int main(int argc, char** argv) {
if (argc < 3) {
fprintf(stdout, "usage: %s <path> <name>\n", argv[0]);
return -1;
}
struct process_info pinfo;
pinfo.path = argv[1];
pinfo.name = argv[2];
pinfo.args = argv[3];
int ret = fork_process(&pinfo);
if (ret == 0) {
char buf[1024 * 4] = {0x00};
int n = read(pinfo.out, buf, 1024 * 4);
if (n > 0) {
buf[n] = 0;
fprintf(stdout, "out: \n%s\n", buf);
} else {
fprintf(stdout, "not found out: %s\n", strerror(n));
}
n = read(pinfo.err, buf, 1024 * 4);
if (n > 0) {
buf[n] = 0;
fprintf(stdout, "err: \n%s\n", buf);
} else {
fprintf(stdout, "not found err: %s\n", strerror(n));
}
} else {
fprintf(stdout, "fork_process return: %d\n", ret);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment