के लिए बाहर निकलने से पहले कई बार fgets loops मैं एक साधारण खोल बना रहा हूँ। इसे लाइनों द्वारा पाठ फ़ाइलों को पढ़ने में भी सक्षम होना चाहिए। यह मेरा कोड है:ईओएफ
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
// Exit when called, with messages
void my_exit() {
printf("Bye!\n");
exit(0);
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
// Char array to store the input
char buff[1024];
// For the fork
int fid;
// Get all the environment variables
char dir[50];
getcwd(dir,50);
char *user = getenv("USER");
char *host = getenv("HOST");
// Issue the prompt here.
printf("%[email protected]%s:%s> ", user, host, dir);
// If not EOF, then do stuff!
while (fgets(buff, 1024, stdin) != NULL) {
// Get rid of the new line character at the end
// We will need more of these for special slash cases
int i = strlen(buff) - 1;
if (buff[i] == '\n') {
buff[i] = 0;
}
// If the text says 'exit', then exit
if (!strcmp(buff,"exit")) {
my_exit();
}
// Start forking!
fid = fork();
// If fid == 0, then we have the child!
if (fid == 0) {
// To keep track of the number of arguments in the buff
int nargs = 0;
// This is a messy function we'll have to change. For now,
// it just counts the number of spaces in the buff and adds
// one. So (ls -a -l) = 3. AKA 2 spaces + 1. Really in the
// end, we should be counting the number of chunks in between
// the spaces.
for (int i = 0; buff[i] != '\0'; i++) {
if (buff[i] == ' ') nargs ++;
}
// Allocate the space for an array of pointers to args the
// size of the number of args, plus one for the NULL pointer.
char **args = malloc((sizeof(char*)*(nargs + 2)));
// Set the last element to NULL
args[nargs+1] = NULL;
// Split string into tokens by space
char *temp = strtok (buff," ");
// Copy each token into the array of args
for (int i = 0; temp != NULL; i++) {
args[i] = malloc (strlen(temp) + 1);
strcpy(args[i], temp);
temp = strtok (NULL, " ");
}
// Run the arguments with execvp
if (execvp(args[0], args)) {
my_exit();
}
}
// If fid !=0 then we still have the parent... Need to
// add specific errors.
else {
wait(NULL);
}
// Issue the prompt again.
printf("%[email protected]%s:%s> ", user, host, dir);
}
// If fgets == NULL, then exit!
my_exit();
return 0;
}
जब मैं इसे खोल के रूप में अकेले चलाता हूं, तो यह बहुत अच्छा काम करता है। जब मैं चलाता हूं ./myshell < command.txt, यह काम नहीं करता है।
commands.txt है:
ls -l -a
pwd
ls
लेकिन उत्पादन होता है:
>Bye!
>Bye!
>Bye!
>Bye!
>Bye!
>Bye!>Bye!
>Bye!
>Bye!
>Bye!
भी मेरी आदेशों को चलाने के नहीं है। कोई विचार? मैंने सोचा कि मेरा लूप बहुत आसान था।
प्रयास करें और कौन क्या मुद्रण को देखने के लिए my_exit() में प्रक्रिया का पीआईडी मुद्रित करें। –
आपको प्रॉम्प्ट प्रिंट करने के बाद कम से कम आउटपुट फ्लश करने की आवश्यकता है ताकि यह कमांड आउटपुट के सापेक्ष सही जगह पर आ जाए। –
पीआईडी को प्रिंट करना, मुझे पिछले 0 को छोड़कर सभी 0 (प्रत्येक अलविदा के लिए!) मिलते हैं, जो 1 9 147 – user1687558