当前位置: 技术问答>linux和unix
Linux 下的c编程问题 子进程
来源: 互联网 发布时间:2016-07-14
本文导语: 模拟Shell的程序 #include #include #include int main(){ char temp[30]; char *command[30]; int i; pid_t pid; while (1){ printf("# "); scanf("%s", temp); printf("%sn", temp); if (strcmp(temp, "exit")==0){ break; } else { command[0] = temp; p...
模拟Shell的程序
#include
#include
#include
int main(){
char temp[30];
char *command[30];
int i;
pid_t pid;
while (1){
printf("# ");
scanf("%s", temp);
printf("%sn", temp);
if (strcmp(temp, "exit")==0){
break;
}
else {
command[0] = temp;
printf("command[0] is %sn", command[0]);
i = 1;
while (getchar()!='n'){
scanf("%s", temp);
command[i] = temp;
printf("command[%d] is %sn", i, command[i]);
i++;
}
command[i] = 0;
pid = fork();
if (pid 0){
wait();
printf("Parent process is running.nn");
}
}
}// end while
printf("Parent process terminated.n");
exit(1);
}// end main
输入:vi file.txt
打印结果:
vi
command[0] is vi
command[1] is file.txt
file.txt
file.txt
想要执行子进程前输出command,发现出错了
#include
#include
#include
int main(){
char temp[30];
char *command[30];
int i;
pid_t pid;
while (1){
printf("# ");
scanf("%s", temp);
printf("%sn", temp);
if (strcmp(temp, "exit")==0){
break;
}
else {
command[0] = temp;
printf("command[0] is %sn", command[0]);
i = 1;
while (getchar()!='n'){
scanf("%s", temp);
command[i] = temp;
printf("command[%d] is %sn", i, command[i]);
i++;
}
command[i] = 0;
pid = fork();
if (pid 0){
wait();
printf("Parent process is running.nn");
}
}
}// end while
printf("Parent process terminated.n");
exit(1);
}// end main
输入:vi file.txt
打印结果:
vi
command[0] is vi
command[1] is file.txt
file.txt
file.txt
想要执行子进程前输出command,发现出错了
|
感觉你这个地方这样做可能有问题:
while (getchar()!='n'){
scanf("%s", temp);
command[i] = temp;
...........
}