首页 文章

C中的fork()和exec()函数

提问于
浏览
0

所以基本上我正在编写一个程序,它重复读取标准输入的输入行,将它们分成char **数组 . 对于每一行,将第一个元素视为要执行的程序的完整路径 . 执行程序,将行上的其余项目作为参数传递 . 如果该行为空,则不执行任何操作并转到下一行 . 重复,直到第一个元素是字符串“exit” .

我的问题是:

  • 当我输入"exit"时,strcmp(l [0],"exit")返回10而不是0.为什么?

  • 程序已编译但仅适用于奇数个参数 . 例如,如果我输入"/bin/echo This is good",则打印"This is good"但是如果输入"/bin/echo This is very good",则打印"error" .

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 10000
int space;
char** createArray(char *line) {
    int len_line = strlen(line);
    char **wordArray = NULL;    
    if(len_line > 1){       
        char *token = strtok(line, " ");    
        space = 0;
        while (token) {
            wordArray = realloc(wordArray, sizeof(char*)*++space);
            wordArray[space-1] = token;
            token = strtok(NULL, " ");
        }
    }
    return wordArray;
}


int main(int argc, const char* argv[]) {    
    char line[BUFSIZE];
    while (1) { 
        printf("%s\n", ">");
        fgets(line, BUFSIZE, stdin);
        char** l = createArray(line);

        if (l) {
            /*why instaed of zero, when l[0] 
            /*equals quit, strcmp() returns 10?*/   
            printf("%d\n", strcmp(l[0], "exit"));       
            if(strcmp(l[0], "exit")==10) {
                exit(0);
            }
            else if(fork() == 0) {
                execv(l[0], l);
                printf("%s\n", "Error!");
            }
        }
    }
    return 1;
}

2 回答

  • 0

    来到你面临的第一个问题

    1. when I input "exit", the strcmp(l[0], "exit") returns 10 instead of 0. Why?
    

    键入“exit”并按Enter键时,fgets读取的字符串为“exit \ n” . 将“exit”与“exit \ n”进行比较得出10.在比较或更改比较方法之前,从末尾删除“\ n”

    if(strcmp(l[0], "exit\n") == 0)
    

    请参阅下面的更正代码

    int main(int argc, const char* argv[]) {
        char line[BUFSIZE];
        while (1) {
            printf("%s\n", ">");
            fgets(line, BUFSIZE, stdin);
            int len = strlen(line);
            line[len - 1] = 0;
            char** l = createArray(line);
    
            if (l) {
                /*why instaed of zero, when l[0]
                 equals quit, strcmp() returns 10?*/
                printf("%d\n", strcmp(l[0], "exit"));
                if(strcmp(l[0], "exit")==0) {
                    exit(0);
                }
                else if(fork() == 0) {
                    execv(l[0], l);
                    printf("%s\n", "Error!");
                }
            }
        }
        return 1;
    }
    

    关于第二个问题

    2. The program got compiled but only works for odd number of arguments. For example, if I input "/bin/echo This is good", it prints "This is good" But if I input "/bin/echo This is very good", it prints "error".
    

    尝试使用下面给出的更正代码 . 有用 . 此问题不再存在 .

  • 1

    你忘了 fgets() 也会返回一个换行符,对吧?

    阅读 fgets() 后,用以下行消除它:

    line[strlen(line) - 1] = '\0';
    

    请再试一次!

相关问题