我想在子进程完成执行时打印它的退出状态。我知道如何在前台进程中做到这一点(使用waitpid)但是在后台进程中,我希望在子进程被fork时立即将命令行访问权授予用户。换句话说,我不能在父进程中等待,而是必须返回到顶部,让while循环再次执行。我很感激一些见解。谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#define MAX_JOBS 100 //max jobs that can go on at once
pid_t jobs[MAX_JOBS];
int job_count = 0;
int last_exit_status = 0;
char* last_termination = 0;
void addJob(pid_t pid) {// Function to add a job to the list
if (job_count < MAX_JOBS) {
jobs[job_count] = pid;
job_count++;
}
}
//main func
int main() {
int x = 0;
char *token;
char *argv[1024]; // Array to store command and arguments
char *argvSec[1024];
int i = 0;
while(x == 0) {
int pid = getpid();
char* command = prompt(); //get user input
if (command != NULL) {
int childExitMethod;
pid_t spwanPID = fork();
switch (spwanPID){
case -1:
last_exit_status = 1;
case 0:
execvp(argv[0], argv);
last_exit_status = 1;
exit(1);
default:
if (isForeGround){
waitpid(spwanPID, &childExitMethod, 0); // Wait for the child only if foreground
if (WIFEXITED(childExitMethod) && !WEXITSTATUS(childExitMethod)) {
last_exit_status = 0;
} else {
printf("bash: %s: command not found\n", command);
last_exit_status = 1;
}
} else if (isBackground){
}
}
}
}
return 0;
}
字符串
1条答案
按热度按时间50pmv0ei1#
我遇到的问题是因为**waitpid(spwanPID,&childExitMethod,0);**阻塞并等待子进程完成运行,因此我无法在分叉后立即给予用户命令行访问权限。(-1,¤tStatus,WNOHANG);**whereWHOHANG停止waitpid阻塞。我可以在prompt函数之前检查子终止。这里有一个例子。
字符串