c - 如何使 Linux 中的脚本使用我的拦截器并工作? (#!)

标签 c linux shell

我为 linux 制作了一个简单的 shell。它使用 getline() 逐行读取,直到将 ctrl+d (eof/-1) 输入标准输入。

当像这样逐行代码进入标准输入时:

ls -al &
ls -a -l

我的 shell 工作得很好。

我试图通过我的 shell 运行脚本,但它不起作用。当我执行脚本时,我的 shell 会自动执行(第一行),但 shell 不会解释其他行。

#!/home/arbuz/Patryk/projekt/a.out
ls -al &
ls -a -l

是什么原因造成的?我不得不说我是 linux 的初学者,老师对所有这些东西都没有说什么。只是一个家庭作业。我已经进行了一些研究,但仅此而已。

这是我的 Shell 代码。我已将 shell 路径添加到 etc/shells 但它仍然无法正常工作

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

int main()
{

    ssize_t bufer_size = 0;
    char* line = NULL;
    int line_size;

    while ((line_size = getline(&line, &bufer_size, stdin)) != -1) // while end of file
    {
        char** words_array;
        words_array = (char**)malloc(200 * sizeof(char*));

        int words_count = 0;
        int i;
        int j = 0;
        int words_length = 0;
        char word[100];
        for (i = 0; i < line_size; i++)
        {
            if (line[i] == ' ' || line[i] == '\n')
            {
                words_array[words_count] = (char*)malloc(words_length * sizeof(char));
                int b;
                for (b = 0; b < words_length; b++)
                {
                    words_array[words_count][b] = word[b];
                }
                j = 0;
                words_count++;
                words_length = 0;
            }
            else
            {
                word[j] = line[i];
                j++;
                words_length++;
            }
        }

        bool run_in_background = false;

        if (words_array[words_count - 1][0] == '&')
        {
            run_in_background = true;
            words_array[words_count - 1] = NULL;
        }

        int a = fork();

        if (a == 0) // child process
        {
            execvp(words_array[0], words_array);
        }
        else       // parent process
        {
            if (run_in_background == true)
            {
                printf("\n ---- running in background. \n");
            }
            else
            {
                printf("\n ---- running normal \n");
                wait(NULL);
            }
        }
    }

    return 0;
}

最佳答案

您的 shell 必须接受命令行参数。在这种情况下,您的程序将这样调用:

/home/arbuz/Patryk/projekt/a.out your_script

So you'll need a main() of this signature:

int main(int argc, char* argv[])

然后解析参数。 argc 包含参数的数量。脚本的文件名在 argv[1] 中传递。您需要打开它(使用 fopen())并从中读取命令而不是 stdin。如果文件以 # 开头,您可能应该确保您的 shell 忽略该文件的第一行。

如果调用脚本时没有绝对路径(不以 / 开头的路径),则文件名是相对于当前目录的。您可以从环境中获取它,也可以使用 getcwd() 以编程方式获取它。

关于c - 如何使 Linux 中的脚本使用我的拦截器并工作? (#!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322119/

相关文章:

bash - 将变量从 shell 脚本传递到 applescript

c - fgetc 打印错误的字符到控制台

linux - tsv 总结 : command not found

bash - 从 shell 命令的响应中获取文本

linux - 为什么 `ping` 在 Linux 中不会超时?

linux - Mongo Shell 坏了

java - 从 Java 运行 bash 文件不起作用

c - 数组左移 (C)

c - 如何在读取前刷新串口?

c++ - 如何解析 HTTP POST(文件上传)流?