c - Linux C Shell,子进程抛出段错误

标签 c linux shell process segmentation-fault

我一直在尝试选择 C ​​语言来完成要求创建 C shell 的家庭作业。一个要求是所有命令都应该从子进程中执行。问题似乎是我的子进程死得太早了,而且我从来没有接触到实际执行命令的代码部分。我的代码:

parseCommand.h

char *parseCommand(char str[]) {
    char * token;
    //get size of the input array. divide memory amount allocated to array by the size of the 1st element (which should be representative of other elements)
    size_t n = sizeof(str) / sizeof(str[0]); 
    char *args = malloc(n);
    printf("Splitting string \"%s\" into tokens:\n", str);
    token = strtok(str, " \n");
    int i = 0;
    while (token != NULL) {
        printf(":: %s\n", token);
        args[i++] = token;
        token = strtok(NULL, " \n");
    }
    printf("after while loop");
    args[i]=(char *) 0;
    return args;

}

ma​​in.c

//I probably don't need all these
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

//Custom Libraries
#include "parseCommand.h"

char *parseCommand(char str[]);

int main() {

    char path[10] = "/bin/";//path to bash scripts
    int should_run = 1;
    while (should_run) {
        printf("yazan_shell>> ");
        fflush(stdout); //force the prompt to the output immediately
        char *cmdStr = (char *)malloc(40); //allocate space for array
        fgets(&cmdStr, 40, stdin); //save user input to cmdStr
        pid_t pid = fork(); //create 
        if (pid == 0) {
            printf("==> Child received: %s command. Executing...\n", &cmdStr);
            char *cmd = parseCommand(&cmdStr);//split user input by space
            printf("cmd: %s", &cmd);
            execvp(strcat(path, cmd[0]), cmd);//excecute the input cmd
        } else {
            int returnStatus;
            waitpid(pid, &returnStatus, 0); //parent waits for child process
            printf("==> Parent is silent!! PID: %d\n", pid);
            should_run = 0;
        }
        free(cmdStr); //deallocate cmdStr
    }
}

输出 1

yazan_shell>> ls -l
==> Child received: ls -l
 command. Executing...
Splitting string "ls -l
" into tokens:
:: ls
:: -l
==> Parent is silent!! PID: 5500

RUN FINISHED; Segmentation fault; core dumped; real time: 3s; user: 0ms; system: 0ms

我几天前才开始学习 C,但我用谷歌搜索了 C 中的段错误,看来我不是在取消引用未初始化的指针,就是在尝试访问已释放的内存。所以我试着注释掉

free(cmdStr);

行,然后输出如下所示:

yazan_shell>> ls -l
==> Child received: ls -l
 command. Executing...
Splitting string "ls -l
" into tokens:
:: ls
:: -l
==> Parent is silent!! PID: 5601

RUN FINISHED; exit value 33; real time: 1s; user: 0ms; system: 0ms

我还尝试在 parseCommand.h 的 while 循环中移动 print 语句,但输出似乎也没有改变。我问过几位有空的 C++ 教授,但他们都无法查明错误。这里有人能给我一些关于我的错误的指示(呵呵)吗?

非常感谢您!

最佳答案

有几个问题-

1.main -

char *cmdStr = (char *)malloc(40);  // don't cast it
fgets(&cmdStr, 40, stdin);        // don't pass address of cmdStr it is already a char *

就这样就好了-

char *cmdStr =malloc(40); 
fgets(cmdStr, 40, stdin); 

2.也在这里-

char *cmd = parseCommand(&cmdStr);//split user input by space
printf("cmd: %s", &cmd);      //cmd is already a char * don't pass its address

这样写——

printf("cmd: %s", cmd); 

3. 在您的函数 char *parseCommand(char str[]) 中计算元素数量时 -

size_t n = sizeof(str) / sizeof(str[0]); 

这不会按预期工作。所以在main中计算n,然后将它传递给你的函数

关于c - Linux C Shell,子进程抛出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33188215/

相关文章:

c++ - 我需要什么工具链来交叉编译 Clang for iOS

c - 理解为什么我需要 malloc

c - 在 C 中编译时如何修复 'undefined reference'?

python - 写入 python multiprocessing.Process 的标准输入

linux - "RUNNINGAS=`/usr/bin/id -un`"是做什么的?

linux - dnf错误: Aborted (core dumped) after packages upgraded from .fc22.x86_64 to .fc22.i686 in fedora 22

java - 无法从 Runtime.exec() 获取输出

c - openssl/sha.h 似乎计算出了错误的哈希值

linux - 重新分配变量时 Shell 脚本无法正常运行

linux - Bash 子 shell 之谜