我在实现自己的手工外壳时遇到了一些麻烦。我已经能够派生一个进程并使用waitpid在前台运行它,但是当我尝试在后台运行简单的进程(例如'sleep 5 &')时,该进程似乎永远运行。checkListJobs 将确定进程是否已完成运行,但它永远不会停止。任何帮助将不胜感激。我认为错误出在我的“foo”函数中。
void insertJob(int pid) {
printf("beginning job %d.\n", pid);
struct job *node = malloc(sizeof(struct job));
node->pid = pid;
node->next = NULL;
if(root == NULL) {
root = node;
} else {
node->next = root;
root = node;
}
}
void checkListJobs(int z) {
curr = root;
while(curr!=NULL) {
if(kill(curr->pid,0) != 0) {
if(prev==NULL) {
prev = curr;
root = curr;
} else {
prev->next = curr->next;
}
} else {
if(!z) printf("%d is still running.\n", curr->pid);
}
prev = curr;
curr = curr->next;
}
}
//code for child forking
void foo(char *cmd, char *argv[], int args) {
int bgFlag;
if(!strcmp(argv[args], "&")){
argv[args] = '\0';
bgFlag = 1;
}
int pid = fork();
int status = 0;
if(pid==0){
if(bgFlag) {
fclose(stdin); // close child's stdin
fopen("/dev/null", "r"); // open a new stdin that is always empty
}
execvp(cmd, argv);
// this should never be reached, unless there is an error
fprintf (stderr, "unknown command: %s\n", cmd);
exit(0);
} else {
if(!bgFlag) {
waitpid(pid, &status, 0);
} else {
insertJob(pid);
}
if (status != 0) {
fprintf (stderr, "error: %s exited with status code %d\n", cmd, status);
} else {
// cmd exec'd successfully
}
}
// this is the parent still, since the child always terminates from exec or exit
// continue being a shell...
}