gpt4 book ai didi

c - C 中的 fork() 和 exec() 函数

转载 作者:行者123 更新时间:2023-11-30 15:21:57 25 4
gpt4 key购买 nike

所以基本上我正在编写一个程序,该程序重复从标准输入读取输入行,并将它们拆分为 char ** 数组。对于每一行,将第一个元素视为要执行的程序的完整路径。执行该程序,并将该行的其余项目作为参数传递。如果该行为空,则不执行任何操作并转到下一行。重复直到第一个元素是字符串“exit”。

我的问题是:

  1. 当我输入“exit”时,strcmp(l[0], "exit") 返回 10 而不是 0。为什么?
  2. 程序已编译,但仅适用于奇数个参数。例如,如果我输入“/bin/echo This is good”,它会打印“This is good”但如果我输入“/bin/echo This is very good”,它会打印“error”。

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 10000
int space;
char** createArray(char *line) {
int len_line = strlen(line);
char **wordArray = NULL;
if(len_line > 1){
char *token = strtok(line, " ");
space = 0;
while (token) {
wordArray = realloc(wordArray, sizeof(char*)*++space);
wordArray[space-1] = token;
token = strtok(NULL, " ");
}
}
return wordArray;
}


int main(int argc, const char* argv[]) {
char line[BUFSIZE];
while (1) {
printf("%s\n", ">");
fgets(line, BUFSIZE, stdin);
char** l = createArray(line);

if (l) {
/*why instaed of zero, when l[0]
/*equals quit, strcmp() returns 10?*/
printf("%d\n", strcmp(l[0], "exit"));
if(strcmp(l[0], "exit")==10) {
exit(0);
}
else if(fork() == 0) {
execv(l[0], l);
printf("%s\n", "Error!");
}
}
}
return 1;
}

最佳答案

您忘记了 fgets() 还返回换行符,对吗?

使用fgets()读取后,使用以下行将其消除:

line[strlen(line) - 1] = '\0';

请再试一次!

关于c - C 中的 fork() 和 exec() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29409600/

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