c - 在c程序中使用exec

标签 c linux command exec

我正在使用 linux,我想用 c 语言编写一个程序,它从用户那里读取命令,直到我输入停止。对于每个命令,主程序将创建一个进程 A,该进程将创建另一个进程 B。进程 B 将执行用户输入的命令。我想让它使用 exec 工作,但它只适用于一个单词命令(例如:pwdls),如果我输入例如 ls -l 它说没有这样的文件或目录。到目前为止我写的代码:

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

#define N 100

int main() {
    char input[N];
    scanf(" %[^\n]s",input); //reads from user inputs that can include space 
    while (strcmp(input,"stop") != 0) { // verifies if entered command == stop
        int a;
        a = fork();//creates the process A
        if (a == -1) {
            perror("fork imposibil!");
            exit(1);
        }
        if (a == 0) {
            printf("a\n");//i printed that to verify if my fork works
            int b;

            b = fork();//creates process B
            if (b == -1) {
                perror("fork imposibil!");
                exit(1);
            }
            if (b == 0) { // the part that makes me problems , i try to use exec to execute the command that is stored in input
                printf("b\n");
                if (execlp(input,"",(char*) 0) < 0) {
                    perror("Error exec");
                    exit(0);
                }
                exit(0);
            }
            wait(0);
            exit(0);
        }
        wait(0);

        scanf(" %[^\n]s",input);
    }
    return 0;
}

有人可以帮我吗? 附言我不认为我的代码难以阅读,但我希望现在更好

最佳答案

在您的示例 ls -l 中,-l 应该传递给参数。

int execlp(const char *file, const char *arg, ...);

引用自help

The function can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

关于c - 在c程序中使用exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29701618/

相关文章:

c - C程序输出错误

c - 如何计算大数之间除法的第一个小数位?

c - 在 C 中打印数组

linux - Raspberry Pi PICAN 在复制预编译内核镜像时出现问题

linux - 如何将具有单列的文本文件转换为矩阵?

linux - 如何更改目录颜色?

python - Python中调用C函数的问题

linux - 在 Linux 中检测程控终止与崩溃

wpf - 多窗口 WPF 应用程序中的命令绑定(bind)

linux - Zip 函数垃圾目录路径