pipes causing infinite output - c

When I simply pipe ls -l | sort with this, the program just spits out the results from ls -l infinitely. Can anyone see what's wrong?
Assume that you only have to look at the main function. This will compile, though.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#define COMMAND_LINE_LENGTH 256
#define HISTORY_LENGTH 10
#define TOKEN_MAX 50
#define DIRECTORY_LENGTH 5
#define DIRECTORY_PREFIX "/bin/"
struct prog_def
{
//Binary location
char *bin;
//Is this program expecting a pipe?
int expecting_pipe;
//Arguments
char *args[TOKEN_MAX + 1];
pid_t pid;
} prog_def;
int get_prog_defs(const char* buf, struct prog_def prog_defs[])
{
char *line = malloc(strlen(buf) + 1);
int prog_count = 0;
char* token;
strcpy(line, buf);
line[strlen(buf)] = 0;
while(1)
{
int arg_count = 0;
//The first time through we have to pass the line
token = strtok(line, " ");
//Each subsequent call we have to pass NULL
//http://www.cplusplus.com/reference/cstring/strtok/
line = NULL;
//Start building the binary location string
prog_defs[prog_count].bin = (char*)malloc(strlen(token) + DIRECTORY_LENGTH + 1);
//Concatenate the directory prefix and command name
strcat(prog_defs[prog_count].bin, DIRECTORY_PREFIX);
strcat(prog_defs[prog_count].bin, token);
//The first argument execvp will expect is the binary location itself
//Redundant but if I wasn't too lazy to read the doc then I'd know why
prog_defs[prog_count].args[arg_count++] = prog_defs[prog_count].bin;
while(1)
{
prog_defs[prog_count].expecting_pipe = 0;
//Check next token for end, pipe, IO redirection, or argument
token = strtok(NULL, " ");
//If we've consumed all tokens
if (token == NULL)
break;
//Pipe
if (strcmp(token, "|") == 0)
{
prog_defs[prog_count - 1].expecting_pipe = 1;
break;
}
//Regular argument
prog_defs[prog_count].args[arg_count++] = token;
}
++prog_count;
if (token == NULL) break;
}
return prog_count;
}
int main(int argc, char** argv)
{
char command[COMMAND_LINE_LENGTH] = {0};
//Generic loop counter
int x = 0;
while(1)
{
printf(">");
//Get the command
gets(command);
struct prog_def prog_defs[TOKEN_MAX];
int prog_count = get_prog_defs(command, prog_defs);
//Keep the previous out fd for the in of the subsequent process
int prev_out_fd = open("/dev/null", O_RDONLY);
for (x = 0; x < prog_count; ++x)
{
//Create a pipe for both processes to share
int pipefd[2];
if (x != prog_count -1)
{
pipe(pipefd);
}
prog_defs[x].pid = fork();
if(prog_defs[x].pid == 0)
{
dup2(prev_out_fd, STDIN_FILENO);
close(pipefd[1]);
if(x != prog_count - 1)
{
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]);
close(pipefd[1]);
}
execvp(prog_defs[x].bin, prog_defs[x].args);
prev_out_fd = pipefd[0];
close(pipefd[1]);
}
close(prev_out_fd);
prev_out_fd = pipefd[0];
close(pipefd[1]);
}
printf("\n");
for (x = 0; x < prog_count; ++x)
{
waitpid(prog_defs[x].pid, NULL, 0);
}
}
}

You call malloc to get some memory for a string, which will be uninitialized, so contain random garbage. You then call strcat which will attempt to append another string to the random garbage and almost certainly run off the end of the malloc'd space, leading to random confusing behavior and crashes.
You also use prog_defs[prog_count - 1] before ever incrementing prog_count, so the first time through the loop, (when prog_count == 0) this will write before the start of the array, which also leads to random confusing behavior and crashes.

Related

Scanf through pipe lock

I have an exercise where I need to interact with a C program through pipe.
I have the following source, which I can't modify.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number;
int answer;
number = rand() % 100;
printf("Print the double of the number %d\n", number);
scanf("%d", &answer);
if(number * 2 == answer)
printf("Success\n");
else
printf("Error\n");
}
I tried to interact with this program with this code
#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv, char **env)
{
int STDIN_PIPE[2];
int STDOUT_PIPE[2];
pipe(STDIN_PIPE);
pipe(STDOUT_PIPE);
pid_t pid = fork();
if(pid == 0)
{
char *path = "/path/to/binary";
char *args[2];
args[0] = path;
args[1] = NULL;
close(STDIN_PIPE[1]);
close(STDOUT_PIPE[0]);
dup2(STDIN_PIPE[0], STDIN_FILENO);
dup2(STDOUT_PIPE[1], STDOUT_FILENO);
execve(path, args, env);
}
else
{
char buf[128];
close(STDIN_PIPE[0]);
close(STDOUT_PIPE[1]);
while(read(STDOUT_PIPE[0], buf, 1))
write(1, buf, 1);
}
}
But when I run it, it falls in an infinite loop without printing nothing.
I have fixed a number of issues in your code, added a lot of error checks and completed it so that the end goal is reached.
In the child process, srand() must be called to initialize the random number generator or you always get the same value.
The in the child process, you must flush(stdout) after printing the question so that it is really written to the pipe.
And finally, scanf() return value must be checked.
In the main process, I added a lot of error checks. And I write a readLine function to - guess what - read a line from the pipe. A line is terminated by the end-of-line character \n.
There is still room for some enhancements...
I tested my code using Visual Studio Code configured for gcc and running under Ubuntu 20.04.
Here is the child process source:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int number;
int answer;
time_t t;
srand((unsigned)time(&t));
number = rand() % 100;
printf("Print the double of the number %d\n", number);
fflush(stdout);
int n = scanf("%d", &answer);
if (n != 1) {
printf("Invalid input\n");
return 1;
}
if ((number * 2) == answer) {
printf("Success\n");
return 0;
}
printf("Error %d is not 2 * %d\n", answer, number);
return 1;
}
And here is the main process source:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int readLine(int fd, char *buf, int bufSize);
int main(int argc, char **argv, char **env)
{
int STDIN_PIPE[2];
int STDOUT_PIPE[2];
if (pipe(STDIN_PIPE))
{
perror("pipe(STDIN_PIPE)");
return 1;
}
if (pipe(STDOUT_PIPE)) {
perror("pipe(STDOUT_PIPE)");
return 1;
}
pid_t pid = fork();
if (pid == 0)
{
char *path = "../Child/Child"; // Path to child process, adapt to your environment
char *args[2];
args[0] = path;
args[1] = NULL;
if (dup2(STDIN_PIPE[0], STDIN_FILENO) == -1) {
perror("dup2(STDIN) failed");
return 1;
}
if (dup2(STDOUT_PIPE[1], STDOUT_FILENO) == -1) {
perror("dup2(STDIN) failed");
return 1;
}
// Close all pipe ends
close(STDIN_PIPE[0]); // Close read end of STDIN_PIPE
close(STDIN_PIPE[1]); // Write end of STDIN_PIPE
close(STDOUT_PIPE[0]); // Read end of STDOUT_PIPE
close(STDOUT_PIPE[1]); // Close write end of STDOUT_PIPE
if (execve(path, args, env) == -1) {
perror("execve failed");
return 1;
}
}
else
{
char buf[128];
int bufSize = sizeof(buf) / sizeof(buf[0]);
int i;
// Read the question asked by child process
if (readLine(STDOUT_PIPE[0], buf, bufSize) < 0) {
printf("readLine failed.\n");
return 1;
}
// We receive something like "Print the double of the number 83"
printf("Child process question is \"%s\".\n", buf);
// Extract the number at end of string
i = strlen(buf) - 1;
while ((i >= 0) && isdigit(buf[i]))
i--;
int value = atoi(buf + i + 1);
// Write our answer to write end of STDIN_PIPE
char answer[128];
int answerSize = sizeof(answer) / sizeof(answer[0]);
int answerLen = snprintf(answer, answerSize, "%d\n", value * 2);
printf("Our answer is \"%d\".\n", value * 2);
if (write(STDIN_PIPE[1], answer, answerLen) != answerLen) {
printf("write failed.\n");
return 1;
}
// Read the response (success or failure) sent by child process
if (readLine(STDOUT_PIPE[0], buf, bufSize) < 0) {
printf("readLine failed.\n");
return 1;
}
if (strcasecmp(buf, "Success") == 0)
printf("Child process returned success.\n");
else
printf("Child process returned failure.\n");
// Close all pipe ends
close(STDIN_PIPE[0]); // Close read end of STDIN_PIPE
close(STDIN_PIPE[1]); // Write end of STDIN_PIPE
close(STDOUT_PIPE[0]); // Read end of STDOUT_PIPE
close(STDOUT_PIPE[1]); // Close write end of STDOUT_PIPE
}
return 0;
}
// Read a line from file descriptor
// A line is any characters until \n is received or EOF
// \n is not kept
// Return the number of characters read or <0 if error:
// -1 => Input buffer overflow
// -2 => read() failed and errno has the error
int readLine(int fd, char *buf, int bufSize)
{
int i = 0;
while (1)
{
// Check if enough room in the buffer
if (i >= bufSize) {
printf("Input buffer overflow\n");
return -1;
}
// Read one character from the pipe
ssize_t n = read(fd, buf + i, 1);
if (n == -1)
{
perror("read() failed");
return -2;
}
if (n == 0)
{
// EOF received, that's OK
return i;
}
// NUL terminate the buffer
buf[i + 1] = 0;
// Check for end of line character
if (buf[i] == '\n') {
buf[i] = 0; // Remove ending \n
return i;
}
i++;
}
}

Address out of bounds in C, problems with making an ls command

I am trying to make a some what shell in C but I am having problems with making the ls command. mkdir, and cd work fine but with ls it gives me
"Address out of bounds segmentation error"
Hope somebody can help me. Here's my code.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
while (1) {
printf("\033[0m%s $", hostname);
input = readline("");
command = get_input(input);
child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
}else if (child_pid == 0) {
/* Never returns if the call is successful */
execvp(command[0], command);
printf("This won't be printed if execvp is successul\n");
} else {
waitpid(child_pid, &stat_loc, WUNTRACED);
}
free(input);
free(command);
}
return 0;
}
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
char *separator = " ";
char *parsed;
int index = 0;
parsed = strtok(input, separator);
while (parsed != NULL) {
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
The only thing I understand it has something to do with memory and references or pointers but I tried changing everything from & refrencing to pointers and it just gave me more errors what do I do?
There were many undeclared variables in your code snippets. You also need to fetch the hostname, it isn't a global variable. It's also a best practice to declare your functions before using them.
This works fine:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>
char **get_input(char *input) {
char **command = malloc(8 * sizeof(char *));
char *separator = " ";
int index = 0;
char *parsed = strtok(input, separator);
while (parsed != NULL && index < 8) { // you need to make sure the index does not overflow the array
command[index] = parsed;
index++;
parsed = strtok(NULL, separator);
}
command[index] = NULL;
return command;
}
int main() {
printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
while (1) {
// hostname does not exist, you need to fetch it
char hostname[1024];
gethostname(hostname, 1023); // POSIX only
printf("\033[0m%s $", hostname);
char *input = readline(NULL);
char **command = get_input(input);
pid_t child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
} else if (child_pid == 0) {
/* Never returns if the call is successful */
execvp(command[0], command);
printf("This won't be printed if execvp is successul\n");
} else {
waitpid(child_pid, NULL, WUNTRACED); // since you don't use the middle argument, no need to point to valid data
}
free(input);
free(command);
}
return 0;
}

Why does my code exit with exit code: 0 even though the loop condition is still valid?

I am trying to use fork with execvp to run two shell commands concurrently. I have two problems which are when I input mkdir folder1&mkdir folder2, it creates a folder named folder1 and another folder named folder2? (the question mark is included in the folder name). The other problem is that the code exits after performing the two commands.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXLINE 80 /* The maximum length command */
int main(void) {
char *args [MAXLINE / 2 + 1]; /* command line arguments */
char *line = (char *) malloc((MAXLINE + 1) * sizeof (char));
char *firstCommand = (char *) malloc((MAXLINE + 1) * sizeof (char));
char *secondCommand = (char *) malloc((MAXLINE + 1) * sizeof (char));
int shouldrun = 1; /* flag to determine when to exit program */
pid_t pid;
while (shouldrun) {
printf("osh>");
fflush(stdout);
fgets(line, MAXLINE, stdin);
if (strncmp(line, "exit", 4) == 0) {
shouldrun = 0;
} else {
firstCommand = strsep(&line, "&");
secondCommand = strsep(&line, "&");
pid = fork();
if (pid == 0) {
// child
if (secondCommand != NULL) {
char *token;
int n = 0;
do {
token = strsep(&secondCommand, " ");
args[n] = token;
n++;
} while (token != NULL);
execvp(args[0], args);
}
} else {
// parent
char *token;
int n = 0;
do {
token = strsep(&firstCommand, " ");
args[n] = token;
n++;
} while (token != NULL);
execvp(args[0], args);
}
}
}
return 0;
}
UPDATE 1:
I tried to follow Kevin's answer. I am trying to execute multiple processes concurrently, e.g. ps&ls&who&date. I tried a recursive method which gave me the same behavior. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXLINE 80 /* The maximum length command */
void execute(char *command) {
char *args [MAXLINE / 2 + 1]; /* command line arguments */
char *parentCommand = strsep(&command, "&");
pid_t pid = fork();;
if (pid == 0) {
// child
if (command != NULL) {
execute(command);
}
} else {
// parent
char *token;
int n = 0;
do {
token = strsep(&parentCommand, " ");
args[n] = token;
n++;
} while (token != NULL);
execvp(args[0], args);
}
}
int main(void) {
char *line = (char *) malloc((MAXLINE + 1) * sizeof (char));
int shouldrun = 1; /* flag to determine when to exit program */
while (shouldrun) {
printf("osh>");
fflush(stdout);
fgets(line, MAXLINE, stdin);
if (strncmp(line, "exit", 4) == 0) {
shouldrun = 0;
} else {
execute(line);
}
}
return 0;
}
For your question about why it doesn't loop, you're calling fork once but calling execvp twice. If successful, execvp will not return. Nothing will get back to run the loop again. What you need to do is call fork once for each execvp. I suggest you move the fork and execvp calls to a separate function:
void run_command(const char* command) {
/* I suggest you also check for errors here */
pid_t pid = fork();
if (pid == 0) {
/* get args, call execvp */
}
}
/* in your loop */
run_command(firstCommand);
run_command(secondCommand);
Regarding the first question, you need to truncate the \n from the line. Regarding the second question, you can use system function from stdlib.h header file which will not terminate your program.

Changing unrelated code gives a segmentation fault. Why is it doing this?

I'm creating my own Shell and I successfully got processes to run in the background by using my is_background function to find a &. It was working fine until i tried to implement redirection of standard output. The chk_if_output function is a part of this as well as the if statement if(out[0] == 1) in the process function. Somehow implementing redirection screwed up the way I implemented background process. If I comment out the redirection code it works again. I get a segmentation fault every time I try to run a background process with the redirection code in the program and I can't for the life of me figure out why. I haven't changed any of the background process code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_LINE 80 /* The maximum length command */
int is_background(char *args[], int size){
int background = 0;
if (strcmp(args[size-1 ], "&") == 0){
background = 1;
args[size-1] = NULL;
}
return background;
}
int * chk_if_output(char *args[], int size){
int * out = malloc(2);
out[0] = 0; out[1] = 0;
for (int i = 0; i < size; i++){
if (strcmp(args[i],">") == 0){
out[0] = 1;
out[1] = i;
break;
}
}
return out;
}
void process(char *command, char *params[], int size){
pid_t pid;
int background = is_background(params, size);
int *out = chk_if_output(params, size);
int fd;
int fd2;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
}else if (pid == 0) {
if(out[0] == 1){
for (int i = out[1]; i < size; i++){
params[i] = params[i+1];
}
fd = open(params[out[1]-1],O_RDONLY,0);
dup2(fd,STDIN_FILENO);
close(fd);
fd2 = creat(params[out[1]],0644);
dup2(fd2,STDOUT_FILENO);
close(fd2);
out[0] = 0;
out[1] = 0;
}
execvp(command, params);
}else {
if(background == 1){
waitpid(pid, NULL, 0);
}
background = 0;
}
}
int main(void) {
char *args[MAX_LINE/2 + 1]; /* command line arguments */
int should_run = 1; /* flag to determine when to exit program */
while (should_run) {
char *line;
char *endline;
printf("Leyden_osh>");
fgets(line, MAX_LINE*sizeof line, stdin);
if((endline = strchr(line, '\n')) != NULL){
*endline = '\0';
}
if (strcmp((const char *)line,"exit") == 0){
should_run = 0;
}
int i = 0;
args[i] = strtok(line, " ");
do{
args[++i] = strtok(NULL, " ");
}while(args[i] != NULL);
process(args[0], args, i);
fflush(stdout);
return 0;
}
In the chk_if_output() function, the last element of the array in the loop was NULL.
Fixed it by looping to size -1.

why wouldn't ls work with execvp?

I have an assignment requesting me to write a mini-shell - something that will get a command to execute, execute it, and wait for some more commands.
when I pass to this mini-shell the command ls . it prints the contest of the current directory. When I pass to it ls it prints nothing. Why?
here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_CMD_SIZE 40
char** parse(char*);//will parse the arguments for the execv/excevp commands.
int main(int argc, char** argv)
{
bool debug = false;
assert(argc <= 2);
if (argc == 2)
{
//check for string -debug
debug = true;
}
if (debug)
printf("INFO: Father started PID[%d]\n", getpid());
char *command = malloc(MAX_CMD_SIZE);
while(true)
{
printf("minishell> ");
fgets(command, MAX_CMD_SIZE, stdin);
if (strcmp(command, "exit\n") == 0)
return 0;
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) //child
{
if (debug)
printf("INFO: Child started PID[%d]\n", getpid());
char** buf = parse(command);
if (debug)
{
int i;
for (i = 0; buf[i]; i++)
printf("INFO: buf[%d] = %s\n",i,buf[i]);
}
execvp(buf[0],buf);
return 0;
}
else //father
{
int status;
wait(&status);
if (debug)
printf("INFO: Child with PID[%d]terminated, continue waiting commands\n", pid);
}
}
}
char** parse(char *string)
{
char** ret = malloc(sizeof(char*));
ret[0] = strtok(string, " ");
int i = 0;
for (; ret[i]; ret[i] = strtok(NULL, " \n"))
{
ret = realloc(ret, sizeof(char*) * ++i);
}
return ret;
}
Your parse() command includes a \n in the last argument :)
So with a single ls, you're actually executing ls\n, which is not in the PATH (of course)
The problem is that on the first strtok() call, you only pass " " as a delimiter. Use " \n" (like in the subsequent calls) and the problem goes away.
You could also fix it by chomping the \n:
int l = strlen (string);
if (l > 0 && string [l - 1] == '\n') string [l - 1] = '\0';
and only using " " as a delimiter.

Resources