我正在深入研究使用C
和&
创建后台作业。为了使其正常工作,我需要实现一个非阻塞的waitpid
。我知道这一点。此外,我已经捕获了如果在命令行末尾输入&
的情况。我只是不确定如何确切地将进程发送到后台作业,并将其实现为在另一个提示正在提示下一个命令时执行。
任何帮助都会很有用,谢谢。
struct bgprocess{
int pid;
struct bgprocess * next;
struct bgprocess * prev;
};
struct bgprocess * bgprocess1;
bgprocess1 = malloc(sizeof(struct bgprocess));
bgprocess1->prev = NULL;
bgprocess1->next = NULL;
bgprocess1->pid = NULL;
struct bgprocess * current;
current = bgprocess1;
do{
int bgreturn = 0;
while (current != NULL){
if (waitpid(current->pid, &bgreturn, WNOHANG)){
printf("Child exited");
current->prev->next = current->next;
current->next->prev = current->prev;
current->prev = NULL;
current->next = NULL;
free(current);
}
current = current->next;
}
if (end){
int pid = fork();
if (pid < 0){
exit(1);
}
if (pid) {
execvp(args[0], args);
exit(0);
}
struct bgprocess * newNode;
newNode = malloc(sizeof(struct bgprocess));
newNode->pid = pid;
newNode->next = NULL;
if (current->next == NULL){
current->next = newNode;
}
while (1){
if (current->next == NULL){
current->next = newNode;
}
current = current->next;
}
}
}
while (current != NULL);
int bgreturn = 0;
while (current != NULL){
if (waitpid(current->pid, &bgreturn,0)){
printf("Child exited");
current->prev->next = current->next;
current->next->prev = current->prev;
current->prev = NULL;
current->next = NULL;
free(current);
}
current = current->next;
}
}
好的,我已经在继续研究这个问题,我认为我可能开始理解了。我仍然有一些语法错误,不知道如何修复,所以我可能会使用gdb或其他工具,除非有人能指出它们。我是正确地处理问题还是完全错误了?
end
是什么?pathlist
是什么?为什么要分叉十个子进程?当似乎你实际上想让你的进程挂起并等待这些睡眠进程时,为什么要使用WNOHANG?你下面说它正在打印'ls'?在哪里?这里没有打印语句。 - FrankieTheKneeMan