#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void main(){
int x,y,status, i;
int cnt = 0;
int flag = 0;
char buf[50];
char str[50];
char * argv[10];
char * ptr;
for(i=0; i<10; i++){
printf("$");
gets(buf);
strcpy(str, buf);
ptr = strtok(buf, " ");
while(ptr != NULL){
argv[cnt] = ptr;
cnt++;
ptr = strtok(NULL," ");
}
if(!strcmp(argv[cnt-1], "&")) {
argv[cnt-1] = 0;
flag = 1;
}
else {
argv[cnt] = 0;
}
if(!strcmp(argv[0],"exit")) exit(0);
x=fork();
if (x==0){
sleep(1);
printf("I am child to execute %s\n", str);
y=execve(argv[0], argv, 0);
if (y<0){
perror("exec failed");
exit(1);
}
}
else {
if(flag == 0) {
wait(&status);
}
}
flag = 0;
cnt = 0;
}
}
我想用'&'执行后台
像真正的 linux shell
所以我分开了
else {
if(flag == 0) {
wait(&status);
}
}
像这样
所以效果很好
如果我输入/bin/ls (没有 &) 提示$放在/bin/ls之后
如果我输入/bin/ls & (with &) 然后提示 $ 放在/bin/ls 之前
但像我第一次进入时一样重写/bin/ls(不带 &) 然后提示 $ 放在/bin/ls 之前
为什么?
===============
$/bin/ls
I am child to execute /bin/ls
ch f1 f2 shell shell.c t t.c test test.c testfile
$/bin/ls &
$I am child to execute /bin/ls &
ch f1 f2 ch f1 f2 shell shell.c t t.c test test.c testfile
$/bin/ls
$I am child to execute /bin/ls
ch f1 f2 shell shell.c t t.c test test.c testfile
================
Is it right?
最佳答案
我会说“$”行为是预期的。
我什至不知道这段代码是如何编译的。您不能使用 void main(){
(至少在使用 gcc 时)。有效形式为 int main() {
。此外,您还可以大大简化代码:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() { /*Changed void main()*/
int x, y, status, i, cnt=0, flag=0; /*Squashed declarations*/
char buf[50]; /*removed str*/
char * argv[10], * ptr;
for(i=0; i<10; i++){
putchar('$'); /*printf() is overkill. Also, watch out for this!*/
fgets(buf, 49, stdin); /*49 (null terminator), gets --> fgets*/
/*strcpy(str, buf); <-- why?*/
ptr = strtok(buf, " ");
while(ptr != NULL) {
argv[cnt++] = ptr;
ptr = strtok(NULL," ");
}
if(!strcmp(argv[cnt-1], "&")) {
argv[cnt-1] = 0;
flag = 1;
} else {
argv[cnt] = 0;
}
if(!strcmp(argv[0],"exit"))
return 0;
x=fork();
if (!x) {
sleep(1);
y=execve(argv[0], argv, 0);
if (y<0) {
perror("execve failed");
return 1;
}
} else {
if(!flag) {
wait(&status);
}
}
flag = 0;
cnt = 0;
}
}
您正在创建 child ,并在每种情况下回显“$” - 这使得“$”出现。
在 fork()
之后,“$”再次显示,即使您正在执行进程也是如此。
关于c - wait() & 在 parent 循环 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317473/