【发布时间】:2013-10-14 11:57:03
【问题描述】:
我正在编写一个 mini-shell,但在作业控制方面遇到了问题。
我无法检索主函数中的数据,甚至无法在 run_command 的底部检索数据。
我想知道如何在 main 中存储和成功检索信息。
typedef struct job{
int num;
pid_t pid[SIZE];
char* name[SIZE];
int occupied;
}
job jobs; <- the global variable
int run_command(........){
. .......
. .......
. result = fork(); // generate child process
. if ( result == 0 ){ //child process
. . if ( 2-pipe function is detected){ // 2 pipe
. . . .......
. . . .......
. . . pid01 = fork(); // fork the first child ( for the first "cat" in case of "cat | cat | cat")
. . . if (pid 01 == 0){
. . . .....
. . . }
. . . else{
. . . . pid02 = fork(); // fork the second child
. . . . if (pid02 == 0){
. . . . .....
. . . . }
. . . . else{
. . . . . pid03 = fork(); // fork the third child
. . . . . if (pid03 == 0){
. . . . . ....
. . . . . }
. . . . . else{
. . . . . . ....
. . . . . . waitpid(pid01,&status1, WUNTRACED);
. . . . . . waitpid(pid02,&status2, WUNTRACED);
. . . . . . waitpid(pid03,&status3, WUNTRACED);
. . . . . . if (WIFSTOPPED(status1)){
. . . . . . jobs.occupied = 1;
. . . . . . jobs.num = 3;
. . . . . . for () {} (a for loop to store the job, i.e. " cat | cat | cat ")
. . . . . . jobs.pid[0] = pid01;
. . . . . . }
. . . . . . if (WIFSTOPPED(status2)){
. . . . . . jobs.pid[1] = pid02;
. . . . . . }
. . . . . . if (WIFSTOPPED(status3)){
. . . . . . jobs.pid[2] = pid03;
. . . . . . }
. . . . . }
. . . . }
. . . }
. . }
. . exit(-1);
. }
. waitpid( result, &status, WUNTRACED);
. if (WIDSTOPPED(status)){
. ....
. }
. ( cannot retrieve jobs here already, like the variable "jobs" has been initialized again)
. return 0;
}
int main(){
.....
.....
.....
run_command(........);
(jobs hasn't been modified after I have press ctrl-z)
return 0;
}
【问题讨论】:
-
你对全局变量的所有赋值都是在第一个孩子中完成的。当然,它们在父级中不可用。
-
如果你的代码缩进太深以至于你认为你需要用点行来显示缩进,那么你需要仔细研究为什么你的代码中没有函数所以事实并非如此深深地缩进。 7 级缩进相当高——不算离谱,但也不好。 Linux 内核样式需要 8 个空格的制表符用于缩进;这鼓励使用函数,因为 7 级缩进意味着代码从第 56 列开始。