简体   繁体   English

我的shell中的联接运算符“;”无法正常工作

[英]The joining operator “;” in my shell isn't working properly

I've written a simple shell in C, and I'm trying to get the ";" 我已经用C语言编写了一个简单的shell,并且试图获取“;” operator working properly, which would be the user typing command1 ; 操作员正常工作,这是用户键入command1; command2 into the command line and the shell executes the first command, followed by the second command. 将command2放入命令行,然后Shell执行第一个命令,然后执行第二个命令。 However, it seems that, for whatever reason, it is only executing the second command. 但是,无论出于何种原因,似乎它只是在执行第二条命令。 Anyone have an idea why? 有人知道为什么吗?

Here is that particular section of my code: 这是我代码的特定部分:

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;
}

Here strchr() function return the value of character pointer after the semi-colon for me. 在这里, strchr()函数为我返回分号后的字符指针值。

If the input is 如果输入是

ls ; ps

strchr() returns strchr()返回

; ps

as a result. 结果是。

Use strtok() instead of strchr() , which is used to split the string as use required. 使用strtok()代替strchr() ,后者用于根据需要分割字符串。

Something like following : 如下所示:

#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;
}

See here 这里

your code is working for me. 您的代码对我有用。 Just have added the condition to handle the corner case. 刚刚添加了条件来处理拐角处的情况。 please check the code in below. 请检查下面的代码。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM