char *c = strtok(a, "|"); // array for the different tokens in the command
char *d = strtok(NULL,"|");
pid_t cpid;
pipe(pfd);
cpid = fork();
if(cpid == 0){
/* child */
cout << "you are in child";
dup2(pfd[0], 0);
close(pfd[0]);
close(pfd[1]); /* the child does not need this end of the pipe */
cout << c;
execString(c);
//perror(cmd2[0]);
cout << "error";
} else{
cpid = fork();
if(cpid == 0){
/* parent */
cout <<"you are in parent";
cout << d;
dup2(pfd[1], 1);
close(pfd[0]);
close(pfd[1]); /* the parent does not need this end of the pipe */
execString(d);
//perror(cmd1[0]);
cout << "error";
} else{
int status;
close(pfd[0]);
close(pfd[1]);
waitpid(cpid, &status, 0);
perror("fork");
exit(1);
}
}
我通过输入ls -l |来测试这段代码wc -l,execstring方法将我的char数组分解为标记并执行它们。我知道这很糟糕,我很久没有做过任何C / C ++了。这很奇怪,因为子进程可以成功执行命令,我仍然可以看到ls -l的输出。我得到的错误来自wc -l,控制台打印回来&#34; wc:无效选项 - &#39;&#39;。尝试使用wc - help获取更多信息。有任何想法吗?
void execString(char *b){
char *tokens = strtok(b, " ");
pid_t child_pid;
int child_status;
child_pid = fork();
vector<char *> commandVector;
while(tokens != NULL){
commandVector.push_back(tokens);
tokens = strtok(NULL," ");
}
cout << tokens << endl;
//cout<< "execString"<<endl;
commandVector.push_back(NULL);
char **args = &commandVector[0];
int status = execvp(args[0], args);
}
答案 0 :(得分:0)
我修好了,管道索引被颠倒了。我将exec命令更改为常量字符串以测试它是否有效。它工作正常。要调整我的execString。