Jump to content

Recommended Posts

Guest mdraganic
Posted

Hello,

 

I was working on an assignment using Windows Subsystem for Linux. Below is the C Code that was used to write a mini-shell for this assignment.

 

I ran into an interesting issue using WSL. On line 35, you can see that I call the read function to read in the buffer and it does a check for null. When pressing Control+D, while using WSL, it will go into the if statement and prints the print message on line 36 infinitely and does not stop until I used CTRL+C to exit. When running this program on a Linux machine, it behaves appropriately and prints once, and brings us to the top of the loop.

 

Any ideas as to what this bug could be?

 

Thanks

 

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/wait.h>

#include <errno.h>

#include <string.h>

#include <sys/types.h>

#include <unistd.h>

#include <error.h>

 

char prompt[] = "$ ";

 

static int

Fork()

{

pid_t pid;

 

if ((pid = fork()) < 0)

error(EXIT_FAILURE, errno, "fork error");

return(pid);

}

 

int

main(void)

{

long MAX = sysconf(_SC_LINE_MAX);

char buf[MAX];

pid_t pid;

int status, n;

 

do {

write(STDOUT_FILENO, prompt, strlen(prompt));

fflush(NULL);

memset(buf, 0, MAX);

if((n = read(STDIN_FILENO, buf, MAX)) == 0) {

printf("use exit to exit shell\n");

continue;

}

buf[strlen(buf) - 1] = '\0'; // chomp '\n'

 

if (strncmp(buf, "exit", MAX) == 0) { // match

break;

}

pid = Fork();

if (pid == 0) { // child

execlp(buf, buf, (char *)NULL);

error(EXIT_FAILURE, errno, "exec failure");

}

// parent

if ((pid = waitpid(pid, &status, 0)) < 0)

error(EXIT_FAILURE, errno, "waitpid error");

} while(1);

exit(EXIT_SUCCESS);

}

 

 

 

The program is in C but there are no options available to insert C Code snippets..

 

More...

  • Replies 0
  • Created
  • Last Reply

Popular Days

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...