C - 等待,获取返回值时失败

时间:2014-01-23 18:12:17

标签: c shell fork wait

我遇到以下问题:在我的代码中,第83行,我有:check = wait(NULL);

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include <sys/stat.h>
#include <sys/types.h>

//---------------------------------
//Function: parse_cmdline(const char* cmdline)
//This function takes the input from stdin
//and returns it as array of strings.
//If stdin is /bin/ls -l /usr/include
//the function will return ["/bin/ls","-l","/usr/include"]
//---------------------------------
char** parse_cmdline(const char* cmdline) {

        int count, word_count = 0;
        char** line_parsed, line_return;
        char *pch, *cmdline_copy = (char*)malloc(sizeof(char)*(strlen(cmdline)+1));
        strcpy(cmdline_copy, cmdline);

        pch = strtok(cmdline_copy," \n\t\r");

        while (pch != NULL) {
                ++word_count;          
        pch = strtok(NULL, " \n\t\r");
        }

        line_parsed = (char**)malloc((word_count+1)*sizeof(char*));
        count = 0;

        strcpy(cmdline_copy, cmdline);
        pch = strtok(cmdline_copy," \n\t\r");

        while (pch != NULL) {          
                line_parsed[count] = (char*)malloc((strlen(pch) + 1)*sizeof(char));
                strcpy(line_parsed[count], pch);
                ++count;
        pch = strtok(NULL," \n\t\r");
        }

        line_parsed[count] = NULL;
        free(cmdline_copy);
        return line_parsed;
}

int main() {

        int count = 0, check;
        size_t size;
        char* line;
        char** cmdline;

        while(1) {

                check = 0;
                printf("$Monkey Eats:< ");
                getline(&line, &size, stdin);
                cmdline = parse_cmdline(line);

                pid_t pid = fork();
                if (pid == -1) {
                        perror("fork");
                        return -1;
                } else if(pid == 0) {
                        struct stat _stat;
                                stat(cmdline[0],&_stat);
                        if(_stat.st_mode & S_IXUSR){   
                                execvp(cmdline[0], cmdline);                           
                        }else fprintf(stderr,"%s: Permission denied!\n",cmdline[0]);
                                perror("");
                        exit(1);
                }else {
                        check = wait(NULL);
                }
                count = 0;
                while(cmdline[count] != NULL) {
                        free(cmdline[count]);
                        ++count;
                }
                free(cmdline);
        }
        return 0;
}

这让我成了问题。当我运行它并输入命令时,我有以下消息:

$Monkey Eats:< ls
ls: Permission denied!
No such file or directory

如果我只有wait(NULL);程序正常运行而没有问题。有人能告诉我这是什么问题吗?谢谢:))

2 个答案:

答案 0 :(得分:1)

问题是尝试运行lsexecvp()不知道ls的位置。尝试运行/bin/ls作为您的命令。

答案 1 :(得分:0)

问题是:stat(cmdline[0],&_stat); - 未检查返回码。如果找不到文件怎么办?程序继续,并发现_stat.st_mode & S_IXUSR为0(随机)。

但是,您可以按“/bin/ls”作为输入来测试程序。