An attempt to realize a shell, mainly a pipeline. I wrote this test case, which I expect will just connect ls to wc ... it definitely does not work properly. It prints ls on the terminal, and then prints out the exhausted memory. I really lost how to fix this and make it work. find_path works in all my tests.
Edit - I need to use execv for the project, its class, but I tried it with execvp just in case, and it does the same. In addition, this is just an example, a test, to understand why it does not work, I call fork for both commands and waitpid twice because I have nothing more to do.
#include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> int find_path(char* execname, char** dst) { char *path = getenv("PATH"); path = strdup(path); char *pos; path = strtok_r(path, ":", &pos); char *originalpath = path; do { char* test = (char*)calloc(strlen(path) + strlen(execname) + 2, sizeof(char)); test = strcpy(test, path); int testlen = strlen(test); (*(test+testlen)) = '/'; strcpy(test + testlen + 1,execname); struct stat buf; int result = stat(test, &buf); if (result == 0) { *dst = test; free (originalpath); return 1; } else { free(test); } } while ((path = strtok_r(NULL, ":", &pos)) != NULL); free(originalpath); return 0; } int main() { char *cmd1 = "ls"; char *cmd2 = "wc"; int filedes[2]; pipe(filedes); char** argv = (char**)calloc(1, sizeof(char*)); argv[0] = (char*)malloc(sizeof(char*)); argv[0] = NULL; pid_t pid = fork(); if (pid == 0) { char *path; find_path(cmd1, &path); dup2(filedes[1],stdout); execv(path,argv); } pid = fork(); if (pid == 0) { dup2(filedes[0], stdin); char *path; find_path(cmd2, &path); execv(path, argv); } else waitpid(pid); }
source share