【发布时间】:2014-01-12 04:02:09
【问题描述】:
我目前正在使用 C 在 shell 中实现 && 功能。例如,如果我们输入 cmd1 && cmd2,则只有在 cmd1 成功退出时才会执行 cmd2。我在想:
int main() {
int i;
char **args;
while(1) {
printf("yongfeng's shell:~$ ");
args = get_line();
if (strcmp(args[0], "exit") == 0) exit(0); /* if it's built-in command exit, exit the shell */
if('&&') parse_out_two_commands: cmd1, cmd2;
if (execute(cmd1) != -1) /* if cmd1 successfully executed */
execute(cmd2); /* then execute the second cmd */
}
}
int execute(char **args){
int pid;
int status; /* location to store the termination status of the terminated process */
char **cmd; /* pure command without special charactors */
if(pid=fork() < 0){ //fork a child process, if pid<0, fork fails
perror("Error: forking failed");
return -1;
}
/* child */
else if(pid==0){ /* child process, in which command is going to be executed */
cmd = parse_out(args);
/* codes handleing I/O redirection */
if(execvp(*cmd, cmd) < 0){ /* execute command */
perror("execution error");
return -1;
}
return 0;
}
/* parent */
else{ /* parent process is going to wait for child or not, depends on whether there's '&' at the end of the command */
if(strcmp(args[sizeof(args)],'&') == 0){
/* handle signals */
}
else if (pid = waitpid(pid, &status, 0) == -1) perror("wait error");
}
}
所以我使用另一个函数 int execute(char ** args) 来完成实际工作。它的返回类型是 int 因为我想知道命令是否成功退出。但是我不确定父进程是否可以从子进程那里获取返回值,因为它们是两个不同的进程。
或者我应该决定是否在子进程中执行第二个命令,通过派生另一个进程来运行它?非常感谢。
【问题讨论】:
-
与你的问题无关,但
strcmp(args[sizeof(args)],'&')至少有两个问题
标签: c linux unix fork parent-child