From f7e0cad06fbabec0ea1a83d8913b6c213dc62c68 Mon Sep 17 00:00:00 2001 From: Matias Linares Date: Tue, 5 Jan 2016 21:21:04 -0300 Subject: Don't close STDIN for the child process. Also this fixes a bug with the argv parameters. The first argument of argv for execvp needs to be the name of the program that is running --- profile.c | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'profile.c') diff --git a/profile.c b/profile.c index 7bccfc4..eea5392 100644 --- a/profile.c +++ b/profile.c @@ -63,8 +63,6 @@ void spawn_child(char *progname, char **args, int fd) close(STDOUT_FILENO); } - close(STDIN_FILENO); - if((execvp(progname, args)) == -1) { fprintf(stderr, "%d - %s\n", errno, strerror(errno)); @@ -93,16 +91,19 @@ int main(int argc, char **argv) usage(argv[0]); return 0; } - prog_name = (char *) calloc(strlen(argv[offset]), sizeof(char)); strcpy(prog_name, argv[offset]); - offset++; if(offset < argc) - args = calloc(argc - offset, sizeof(char*)); + args = calloc(argc - offset + 1, sizeof(char*)); + /* The last parameter of the argv needs to be NULL. */ for(int i = offset; i < argc; i++) - args[i - offset] = argv[i]; + { + args[i - offset] = (char *) calloc(strlen(argv[i]) + 1, sizeof(char)); + strncpy(args[i - offset], argv[i], strlen(argv[i])); + } + args[argc - offset] = NULL; if((curpid = fork()) < 0) { @@ -117,7 +118,7 @@ int main(int argc, char **argv) { /* Open the outfile with 664 permissions. */ fd_out = open(out_file, - O_WRONLY | O_CREAT, + O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); } spawn_child(prog_name, args, fd_out); @@ -152,5 +153,14 @@ int main(int argc, char **argv) #endif } + /* Clean up */ + if(prog_name) + free(prog_name); + for(int i = 0; i < argc - offset + 1; ++i) + if(args[i] != NULL) + free(args[i]); + if(args) + free(args); + return status; } -- cgit v1.2.3-70-g09d2