【发布时间】:2013-12-09 18:23:26
【问题描述】:
我正在尝试用 C 编写一个非常基本的 shell 程序。我面临的问题是试图用从输入中获取的单词填充我的 argv 字符指针数组。当我尝试使用下面的 parse() 函数填充 argv 数组的内容后尝试打印它时,出现分段错误。我知道这意味着我可能正在尝试访问超出范围的 argv 数组的一部分。但是,即使只提供一个参数来填充数组,我仍然会遇到段错误。用于打印 argc 的 printf 调用根据输入返回正确的 argc 值,但带有 *argv[0] 的第二个 printf 调用是导致段错误的调用。我想知道我的错误是我尝试打印 argv 内容的方式,还是因为我试图错误地填充 argv。
编辑:我应该补充一点,getword() 函数接收一行文本并返回由空格分隔的第一个单词,以及许多其他分隔符。如有必要,我可以张贴所有将单词分开的分隔符,但我认为问题不是因为 getword()。
编辑2:在头文件中添加并在main中包含#include语句。
编辑3:在main()下添加getword函数,在p2.h下添加getword.h
这里是p2.h,main中包含的头文件:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "getword.h"
#include <signal.h>
#define MAXITEM 100
getword.h:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
int getword(char *w);
int parse(char *, char *[]);
这里是主要功能:
#include "p2.h"
int main() {
pid_t pid, child_pid;
int argc, inputRedirect;
char *devNull;
devNull = (char *) malloc(10);
strcpy(devNull, "/dev/null");
char *argv[MAXITEM];
char commandLine[STORAGE];
for (;;) {
printf("p2: ");
scanf("%s", commandLine);
argc = parse(commandLine, argv);
printf("argc = %d\n", argc);
if(argc == 0)
continue;
printf("*argv = %s\n", *argv[0]);
child_pid = fork();
if (child_pid < 0) {
printf("Cannot fork! Terminating...");
exit(1);
} else if (child_pid == 0) {
inputRedirect = open(devNull, O_RDONLY);
dup2(inputRedirect, STDIN_FILENO);
close(inputRedirect);
execvp(*argv, argv);
}
else {
for(;;) {
pid = wait(NULL);
if(pid == child_pid)
break;
}
printf("Child's pid is %d\n", child_pid);
}
}
killpg(getpid(), SIGTERM);
printf("p2 Terminated.\n");
exit(0);
}
int parse(char *commandLine, char *argv[]) {
int i, argc = 0;
char *commandPointer = commandLine;
while (*commandPointer != '\0') {
*argv = commandPointer;
argc++;
getword(commandPointer);
}
*commandPointer = '\0';
*argv = '\0';
return argc;
}
getword.c:
#include "getword.h"
#include <stdlib.h>
/*Function Prototypes*/
int tilde(char *p, int i);
int BSFollowedByMetaCharacter(int c, char *w);
int getword(char *w) {
int c;
int index = 0;
/*This while loop removes all leading blanks and whitespace characters
* The if statement then tests if the first character is a new line or
* semicolon metacharacter*/
while ((c = getchar()) == ' ' || c == '\t' || c == '\n' || c == ';') {
if (c == '\n' || c == ';') {
w[index] = '\0';
return 0;
}
}
/*This if statement calls ungetc() to push whatever character was taken
* from the input stream in the previous while loop back to the input
* stream. If EOF was taken from the input stream, ungetc() will return EOF,
* which will then cause getword() to return -1, signalling that it reached
* the End Of File. */
if (ungetc(c, stdin) == EOF)
return -1;
/*This if statement deals with some of the "non-special" metacharacters.
* If one of these metacharacters is pulled from the input stream by getchar(),
* it is stored in w and null-terminated. getword() then returns the length of
* the current string stored in w. If getchar() pulls anything besides one of the
* specified metacharacters from the input stream, it is then returned using ungetc() after
* the if statement.*/
if ((c = getchar()) == '<' || c == '>' || c == '|' || c == '&') {
w[index++] = c;
int d = getchar();
if (c == '>' && d == '>')
w[index++] = d;
else {
ungetc(d, stdin);
}
w[index] = '\0';
return index;
}
ungetc(c, stdin);
/*This while statement handles plain text from the input stream, as well as a few 'special'
* metacharacters. It also ensures that the word scanned is shorter than STORAGE-1 bytes.*/
while ((c = getchar()) != ' ' && c != '<' && c != '>' && c != '|'
&& c != ';' && c != '&' && c != '\t' && c != '\n' && c != '\0'
&& index <= STORAGE - 1) {
if (c == '~') {
int *ip = &index;
index = tilde(&w[index], *ip);
continue;
}/*END IF*/
else if (c == '\\') {
int d = c;
c = getchar();
if (BSFollowedByMetaCharacter(c, w)) {
w[index++] = c;
continue;
} else {
w[index++] = d;
}
}/*END ELSE IF*/
w[index] = c;
index++;
}/*END WHILE*/
ungetc(c, stdin);/*This final ungetc() call is used to push any meta characters*/
w[index] = '\0'; /*used as delimiters back to the input stream, to be retrieved*/
return index; /*at the next call of getword(). */
}/*END getword()*/
int tilde(char *cp, int i) {
int *ip;
ip = &i;
char *p = cp;
char *o;
o = (strcpy(p, getenv("HOME")));
int offset = strlen(o);
*ip = *ip + offset;
return i;
}
int BSFollowedByMetaCharacter(int c, char *w) {
if (c == '~' || c == '<' || c == '>' || c == '|' || c == ';' || c == '&'
|| c == ' ' || c == '\t' || c == '\\') {
return 1;
} else {
return 0;
}
}
【问题讨论】:
-
char *devNull; devNull = (char *) malloc(10); strcpy(devNull, "/dev/null");是你能做的最糟糕的事情。您无缘无故地进行堆分配,未能释放分配的内存,从而泄漏了它。您还投射了malloc()的返回值,这是错误的。为什么不直接写const char *devNull = "/dev/null";? -
感谢@H2CO3 的输入,我做了您建议的更改。我认为由于将在整个程序中使用 devNull 指针,因此在堆上分配空间会更有意义,但忽略了 const char * 的想法。但是,在尝试打印 argv 时,我仍然遇到段错误。我应该尝试通过取消引用 argv[0] 两次来打印它吗?比如:"printf("*argv = %s\n", **argv[0]);"?
-
顺便问一下,您是否尝试过在调试器中运行您的代码?
-
当您尝试发布您正在使用的代码(而不是一段代码)时,我建议您发布 full 代码,其中包括必要的标头和宏定义,并且应该能够编译&运行&重现你的问题。
-
@trawww 那么你应该尝试将 printf 行修改为` printf("*argv = %s\n", argv[0]);` 因为
argv[0]已经是char*类型并且在用于 %s`` 时不应被取消引用
标签: c arrays shell printf char-pointer