Skip to content

Instantly share code, notes, and snippets.

@qianjigui
Created March 19, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qianjigui/9641158 to your computer and use it in GitHub Desktop.
Save qianjigui/9641158 to your computer and use it in GitHub Desktop.
Child Process zombie OR pipe block error. 如果父进程没有主动回收子进程的return status且父进程没有退出, 子进程在exit后进行zombie状态;进程间建立了pipe,一方关闭将导致另一方无法通信且默认会block
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
int pipe_fd[2];
pid_t pid;
char r_buf[10];
char test[10];
int res;
strcpy(test,"just test");
memset(r_buf,0,sizeof(r_buf));
if(pipe(pipe_fd)<0)
{
printf("pipe create error ");
return -1;
}
int readpipe = pipe_fd[0];
int writepipe = pipe_fd[1];
if((pid=fork())>0)//父进程:解析从管道中获取的命令,并作相应的处理
{
close(writepipe);
//read(readpipe,r_buf,10);//default options will block this invoke
//close(readpipe);//If closed, the child will block @ write
while(1){
printf("Self=%d,Child=%d\n",getpid(),pid);
sleep(20);
waitpid(pid, &res, WNOHANG);//Without this line, the child return status will be lost, and the child will convert to zombie process
}
} else if(pid==0) {
//child: send commands to parent
printf("create child process successfully\n");
close(readpipe);
printf("Child Sleep 10s\n");
sleep(1);
printf("Self=%d,Parent=%d\n",getpid(),getppid());
res=write(writepipe,test,sizeof(test));//Will block if its parent's readpipe is closed before this write
printf("res=%d,%s\n",res,strerror(errno));
close(writepipe);//Even if the child has exit, but the parent does NOT get return value, this child will be zombied
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment