Linux ./a.out 之后,是在什么情况下会进入命令行?是父进程结束之后便会进入命令行吗?

胖胖的小肥猫 2020-08-11 10:10:45
哥哥姐姐们,我写了一个孤儿进程
程序运行的结果 却是 这样的

第一次,./a.out 父进程结束之后,便进入了命令行,而此时,子进程还没有结束,便在命令行后面打印出了 子进程 的内容。
请问,是因为 init 进程是一个后台进程,所以,linux 在检测到** 父进程结束之后,便打印出 命令行了吗?**

可是,我同学说,在他的 linux 中,没有出现这个现象。


这是由于什么原因呢? 和虚拟机的内核数有关吗?

以下为源代码

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main(){
// 声明:int pipe(int pipefd[2]);
int fd[2];
char buf[128];
if(pipe(fd) < 0 ){
printf("creat pipe failed \n");
exit -1;
}
// printf("it is ok \n");
int pid;
pid = fork(); // fork() 创建 一个进程
if( pid < 0){
printf("creat son failed\n");
}
else if(pid > 0){
printf("into father \n");
close(fd[0]);
write(fd[1],"write from father",strlen("write from father"));
// printf("write is over \n");
}
else{
printf("pid = %d, into son\n",pid);
close(fd[1]);
read(fd[0],buf,128);
printf("read from father : %s\n",buf);
}
return 0;
}
...全文
5056 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
alittlenewbiek 2020-08-13
  • 打赏
  • 举报
回复
我想,可能是你的系统处理慢了一点。你让同学在child process(pid == 0)的处理中加入sleep(1),应该也会出现和你同样的现象。

command line什么时候拿回控制权?
shell本身是一个进程,
通过shell调用程序后,相当于shell是父进程,被调用程序是子进程;
当子进程结束后,控制权回到父进程;
但是,父进程只知道自己的子女,并不知道孙子輩。

假如shell的进程用A表示,a.out的进程用B表示,a.out产生的子进程用C表示,
那么,A知道B,并在B结束后,控制权回到A手中;
A不知道C,A不会等待C有没有结束。

但如果我们想让A等待B和C,也可以,调用wait(man 2)函数,比如
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include <sys/wait.h> // wait() requires this header file

int main()
{
int fd[2];
char buf[128] = {0};
if(pipe(fd) < 0 )
{
printf("creat pipe failed \n");
exit(-1);
}

int pid;
pid = fork();
if( pid < 0)
{
printf("creat son failed\n");
}
else if(pid > 0)
{
int status;
printf("pid = %d, into father\n", pid);
close(fd[0]);
write(fd[1], "write from father", strlen("write from father"));
wait(&status); // call wait in calling process
}
else
{
sleep(1); // no matter how long it sleeps
printf("pid = %d, into son\n", pid);
close(fd[1]);
read(fd[0],buf,128);
printf("read from father : %s\n", buf);
}
return 0;
}


最后,
如果B进程还没有结束,C提前结束,并且B没有wait(),
C的进程被标记为zombie,这样并不好,因为zombie进程会占用内核的资源,多一个zombie就少一个可产生的进程,
但是如果B进程也结束了,zombie进程会过继给init(pid=1)进程,init会自动调用wait()来结束zombie。

以上,conforming to kernel 2.6 and POSIX.1-2001

23,217

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧