我正在尝试使用c解析shell脚本中的命令。我目前设置了链表,但我在正确删除和返回第一个元素时遇到了麻烦。当我试着得到第一个元素的时候,它可以正常工作一次,但是之后它就卡住了,进入了一个无限循环,我不明白为什么。提前感谢任何帮助。下面是我的代码:
enum command_type
{
AND_COMMAND, // A && B
SEQUENCE_COMMAND, // A ; B
OR_COMMAND, // A || B
PIPE_COMMAND, // A | B
SIMPLE_COMMAND, // a simple command
SUBSHELL_COMMAND, // ( A )
};
// Data associated with a command.
struct command
{
enum command_type type;
// Exit status, or -1 if not known (e.g., because it has not exited yet).
int status;
// I/O redirections, or null if none.
char *input;
char *output;
union
{
// for AND_COMMAND, SEQUENCE_COMMAND, OR_COMMAND, PIPE_COMMAND:
struct command *command[2];
// for SIMPLE_COMMAND:
char **word;
// for SUBSHELL_COMMAND:
struct command *subshell_command;
} u;
};
typedef struct command_stream *command_stream_t;
typedef struct command *command_t;
struct command_stream
{
command_t command_stream;
command_stream_t next;
}
command_t
read_command_stream(command_stream_t s)
{
if(s)
{
command_t comm = s->command;
s=s->next;
return comm;
}
return NULL;
}
void printList(command_stream_t head)
{
command_t command;
while((command = read_command_stream(head)))
{
//print_command is a function that takes in a command_t and then prints the
//command in a nice format.
print_command(head->command);
}
}
在这个函数中,您正在修改指针的本地副本(不是您传递的主指针),因此您的head
指针永远不会移动。
command_t
read_command_stream(command_stream_t s)
{
if(s)
{
command_t comm = s->command;
s=s->next;
return comm;
}
return NULL;
}
你需要改变这个函数来接受指针对指针的,如果你不理解这个概念,我建议一本好书(或教程)会让你开始