繁体   English   中英

在C程序中使用exec

[英]use exec in c program

我正在使用linux,我想用c语言编写一个程序,以读取用户的命令,直到我输入stop。对于每个命令,主程序将创建一个进程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, ...);

帮助中的引用说

可以将函数视为arg0,arg1,...,argn。 它们一起描述了一个或多个指向以空值结尾的字符串的指针的列表,这些字符串表示可用于执行的程序的参数列表。 按照惯例,第一个参数应指向与正在执行的文件关联的文件名 参数列表必须以NULL指针终止,并且由于它们是可变参数函数,因此必须将该指针强制转换为(char *)NULL。

您没有按照期望的方式将参数传递给函数execlp()。

这些函数的初始参数是要执行的文件的名称。

const char * arg和execl(),execlp()和execle()函数中的后续省略号可以被视为arg0,arg1,...,argn。 它们一起描述了一个或多个指向以空值结尾的字符串的指针的列表,这些字符串表示可用于执行的程序的参数列表。 按照惯例,第一个参数应指向与正在执行的文件关联的文件名。 参数列表必须以NULL指针终止,并且由于它们是可变参数函数,因此必须将该指针强制转换为(char *)NULL。

看一下有关如何使用execlp()函数的解释- 我不明白execlp()在Linux中的工作方式

我猜您将不得不使用带有定界符" "的字符串分隔符功能来获取命令行参数,例如-lls -l

strtok()在C语言中提供此功能。

#include <string.h>
#include <stdio.h>

int main(void)
{
    char input[] = "A bird came down the walk";
    printf("Parsing the input string '%s'\n", input);
    char *token = strtok(input, " ");
    while(token) {
        puts(token);
        token = strtok(NULL, " ");
    }

    printf("Contents of the input string now: '");
    for(size_t n = 0; n < sizeof input; ++n)
        input[n] ? printf("%c", input[n]) : printf("\\0");
    puts("'");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM