壳牌程序管道C [英] Shell program pipes C
问题描述
我正在尝试运行一个小的Shell程序,确保我的代码正常运行的第一步是确保获得正确的命令和参数:
I am trying to run a small shell program and the first step to make sure my code is running properly is to make sure I get the correct command and parameters:
//Split the command and store each string in parameter[]
cp = (strtok(command, hash)); //Get the initial string (the command)
parameter[0] = (char*) malloc(strlen(cp)+ 1); //Allocate some space to the first element in the array
strncpy(parameter[0], cp, strlen(cp)+ 1);
for(i = 1; i < MAX_ARG; i++)
{
cp = strtok(NULL, hash); //Check for each string in the array
parameter[i] = (char*) malloc(strlen(cp)+ 1);
strncpy(parameter[i], cp, strlen(cp)+ 1); //Store the result string in an indexed off array
if(parameter[i] == NULL)
{
break;
}
if(strcmp(parameter[i], "|") == 0)
{
cp = strtok(NULL, hash);
parameter2[0] = (char*) malloc(strlen(cp)+ 1);
strncpy(parameter2[0], cp, strlen(cp)+ 1);
//Find the second set of commands and parameters
for (j = 1; j < MAX_ARG; j++)
{
cp = strtok(NULL, hash);
if (strlen(cp) == NULL)
{
break;
}
parameter2[j] = (char*) malloc(strlen(cp)+ 1);
strncpy(parameter2[j], cp, strlen(cp)+ 1);
}
break;
}
比较cp和NULL时出现问题,程序崩溃.我想要的是在第二个集合或参数的输入完成后退出循环(这是我尝试使用if(strlen(cp)== NULL)进行的操作
I am having a problem when I compare cp and NULL, my program crashes. What I want is to exit the loop once the entries for the second set or parameters have finished (which is what I tried doing with the if(strlen(cp) == NULL)
推荐答案
我可能误解了这个问题,但是您的程序永远不会参见管道字符|
.
I may have misunderstood the question, but your program won't ever see the pipe character, |
.
shell处理整个命令行,可以这么说,您的程序只会获得其在命令行中的份额.
The shell processes the entire command line, and your program will only be given it's share of the command line, so to speak.
示例:
cat file1 file2 | sed s/frog/bat/
在上面的示例中,仅使用两个参数file1
和file2
调用cat
.另外,sed
仅用一个参数调用:s/frog/bat/
.
In the above example, cat
is invoked with only two arguments, file1
, and file2
. Also, sed
is invoked with only a single argument: s/frog/bat/
.
这篇关于壳牌程序管道C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!