
作业社区
探索学习新天地,共享知识资源!
FishKylin 的学生作业:
#include #include #include #include #include #include #define COMMADN_MAX 1024 #define ARGS_MAX 5 char * s_gets(char *str, int n); char ** parse_command(char *str, char **args, int args_number); int main(void) { pid_t pid; char command[COMMADN_MAX]; char *args[ARGS_MAX + 1]; while (s_gets(command, COMMADN_MAX)) { parse_command(command, args, ARGS_MAX); if ((pid = fork()) == -1) { perror("Fork: "); exit(EXIT_FAILURE); } else if (pid == 0) { if (execvp(args[0], args) == -1) { perror("Execvp: "); exit(EXIT_FAILURE); } exit(900); } int status; waitpid(pid, &status, 0); printf("Child process %d exit status %d\n", pid, WEXITSTATUS(status)); } return 0; } // 获取输入去掉换行符 char * s_gets(char *str, int n) { char *ret_val = fgets(str, n, stdin); if (ret_val) { char *find = strchr(str, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } // 解析输入并存储 char ** parse_command(char *str, char **args, int args_number) { char *temp; int index = 0; if (str) { temp = strtok(str, " "); while (temp && index < args_number) { args[index++] = temp; temp = strtok(NULL, " "); } } args[index] = NULL; return args; }





FishKylin 的学生作业:
#include #include #include #include #include int main(void) { pid_t sub_apid, sub_bpid; if ((sub_apid = fork()) < 0) { perror("fork:"); exit(EXIT_FAILURE); } else if (sub_apid == 0) { printf("Process A Started: %d\n", getpid()); sleep(2); printf("Process A Exiting: %d\n", getpid()); exit(101); // 因为子进程在这里已经退出,所以后续父进程代码不会被执行 } if ((sub_bpid = fork()) < 0) { perror("fork:"); exit(EXIT_FAILURE); } else if (sub_bpid == 0) { printf("Process B Started: %d\n", getpid()); sleep(5); printf("Process B Exiting: %d\n", getpid()); exit(102); // 因为子进程在这里已经退出,所以后续父进程代码不会被执行 } int astatus; pid_t a_wait = waitpid(sub_apid, &astatus, 0); if (a_wait > 0) { printf("Sub A process %d exit, status: %d\n", a_wait, WEXITSTATUS(astatus)); } else { perror("wait A failed:"); } int bstatus; pid_t b_wait = waitpid(sub_bpid, &bstatus, 0); if (b_wait > 0) { printf("Sub B process %d exit, status: %d\n", b_wait, WEXITSTATUS(bstatus)); } else { perror("wait B failed:"); } return 0; }




