gpt4 book ai didi

c - 迷你外壳中的 strtok 和 execlp

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:41 25 4
gpt4 key购买 nike

我正在编写一个迷你 shell 以更熟悉 C 中的 Unix 进程管理。它从命令行读取内容并通过 execlp 将这些参数传递给系统。

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

#define MAXSIZE 100

char prompt[MAXSIZE];

int main(void)
{
pid_t pid;

printf("> ");

// read stuff
if (fgets(prompt, MAXSIZE, stdin) == NULL){
printf("Input validation error!");
abort();
}
// printf("DEBUG: %s" , prompt);

if (strcmp(prompt, "exit")==0) abort();


if ((pid=fork())<0){ // copy process

printf("Process error!");
abort();
}

if (pid==0){ // exec in son-prcess

char *command=(char*)strtok(prompt, " ");
execlp(command, command, 0); // overwrite memory

printf("Error, command not found!");
abort();
} else {

waitpid(pid, 0, 0);
}
}

事实上就是这样,但我没有从 execlp() 得到任何输出。有人知道这是为什么吗?

最佳答案

我尝试运行您的程序但失败了,因为 command 包含 \n(换行符)。我通过在 strtok 中放置 \n 而不是 ""来更改它,然后它成功运行。

详细说明:

  if (pid==0){                // exec in son-prcess
char *command=(char*)strtok(prompt, "\n");
printf ("'%s'\n", command);
execlp (command, command, 0); // overwrite memory
printf("Error %d (%s)\n", errno, strerror (errno));
abort();
} else {

测试运行:

$ ./a.out > ls'ls'(usual ls behaviour)

关于c - 迷你外壳中的 strtok 和 execlp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1651044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com