C 我的shell中的联接运算符“;”工作不正常
我已经用C编写了一个简单的shell,我正在尝试获取;操作员工作正常,这将是用户键入command1;命令2进入命令行,shell执行第一个命令,然后执行第二个命令。然而,无论出于何种原因,它似乎只是在执行第二个命令。有人知道为什么吗 以下是我的代码的特定部分:C 我的shell中的联接运算符“;”工作不正常,c,shell,C,Shell,我已经用C编写了一个简单的shell,我正在尝试获取;操作员工作正常,这将是用户键入command1;命令2进入命令行,shell执行第一个命令,然后执行第二个命令。然而,无论出于何种原因,它似乎只是在执行第二个命令。有人知道为什么吗 以下是我的代码的特定部分: char* next = strchr(cmd, ';'); while (next != NULL) { /* 'next' points to ';' */ *next = '\0'; input = ru
char* next = strchr(cmd, ';');
while (next != NULL) {
/* 'next' points to ';' */
*next = '\0';
input = run(cmd, input, first, 0);
cmd = next + 1;
next = strchr(cmd, ';');
first = 0;
}
这里strhr函数为我返回分号后字符指针的值
如果输入是
ls ; ps
strhr返回
结果,
使用而不是strchr,后者用于根据需要拆分字符串
大致如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *str = malloc(20);
char *tok = NULL;
strcpy(str, "command1;command2");
tok = strtok(str, ";");
while (tok)
{
printf("Token: %s\n", tok);
tok = strtok(NULL, ";");
}
free(str);
return 0;
}
请参见您的代码对我有效。刚刚添加了处理拐角案例的条件。请检查下面的代码
char* next = strchr(cmd, ';');
while (next != NULL) {
/* 'next' points to ';' */
*next = '\0';
input = run(cmd, input, first, 0);
printf ("%s\n",cmd );
cmd = next + 1;
next = strchr(cmd, ';');
if (NULL ==next ){
input = run(cmd, input, first, 0);
printf ("%s\n",cmd );
}
first = 0;
}
cmd可能有问题,例如,它是字符串文字谢谢您的回答。我尝试了你的编辑,但是当我键入ls时;ps进入命令行,它表示分段错误,然后执行第二个命令。知道为什么吗?我没有运行api。所以它可能会在里面崩溃。ls;ps有额外的空间。你可以像ls一样尝试;附言
char* next = strchr(cmd, ';');
while (next != NULL) {
/* 'next' points to ';' */
*next = '\0';
input = run(cmd, input, first, 0);
printf ("%s\n",cmd );
cmd = next + 1;
next = strchr(cmd, ';');
if (NULL ==next ){
input = run(cmd, input, first, 0);
printf ("%s\n",cmd );
}
first = 0;
}