[英]how to execute terminal commands in C
我正在嘗試模擬一個終端,在我的代碼中幾乎所有命令都可以很好地執行,但是當我嘗試執行這些沒發生的事情時,命令cd文件夾和cd ..可以幫我這個忙嗎
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLEN 100
#define TRUE 1
#define FALSE 0
typedef struct command {
char *cmd; // string apenas com o comando
struct command *next; // apontador para o próximo comando
} COMMAND;
COMMAND *insert(COMMAND *list, char *cmd);
COMMAND *startList();
int strCompare(char *str1, char *str2);
int strLenght(char *str);
int main(void) {
char command[MAXLEN] = "start";
int id, return_command = 0;
COMMAND *commands = startList();
char exit_com[5] = "exit\0";
int r;
while(r = strCompare(command, exit_com)){
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL){
fprintf(stdout, "%s: ", cwd);
}
fgets(command, MAXLEN, stdin);
commands = insert(commands, command);
id = fork();
if (id == 0){
return_command = system(command);
if (return_command == -1){
printf("\nErro ao executar o comando '%s'\n", command);
exit(0);
}
COMMAND *c = commands;
while(c != NULL){
printf("%s\n", c->cmd);
c = c->next;
}
exit(0);
}
wait(id);
}
return 0;
}
int strCompare(char *str1, char *str2){
char aux = str2[0];
int i = 0;
while(aux != '\0'){
if (str1[i] != str2[i])
return 1;
aux = str2[++i];
}
return 0;
}
COMMAND *startList(){
return NULL;
}
COMMAND *insert(COMMAND *list, char *cmd){
COMMAND *newCommand = (COMMAND*) malloc(sizeof(COMMAND));
newCommand->cmd = cmd;
newCommand->next = list;
return newCommand;
}
這是因為system
功能啟動了一個新進程,因此您在system
運行的每個命令都將僅位於該進程中。 這就是外殼程序通常在內部處理諸如cd
命令的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.