代码如下所示:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void sig_child()
{
printf("child terminated\r\n");
}
int main(int argc, const char *argv[])
{
int pipefd[2];
char buf[100]={0};
pid_t pid;
// Create a pipe for interprocess communication
if(pipe(pipefd)<0)
{
perror("pipe");
exit(EXIT_FAILURE);
}
// Create a process use fork
pid=fork();
if(pid > 0)
{
#if 0
printf("###id=[%d]###\n",pid);
printf("###pid=[%d]###\n",getpid());
printf("###ppid=[%d]###\n",getppid());
#endif
printf( "This is in the father process,here write a string to the pipe.\n" );
char buf[] = "Hello world , this is write by pipe.\n";
write( pipefd[1], buf, sizeof(buf) );
close( pipefd[0] );
close( pipefd[1] );
}
else if(pid == 0)
{
#if 0
printf("###id=[%d]###\n",pid);
printf("###pid=[%d]###\n",getpid());
printf("###ppid=[%d]###\n",getppid());
#endif
printf( "This is in the child process,here read a string from the pipe.\n" );
read( pipefd[0], buf, sizeof(buf) );
printf( "%s\n", buf );
close( pipefd[0] );
close( pipefd[1] );
}
//signal(SIGCHLD,sig_child);
waitpid( pid, NULL, 0 );
return 0;
}
1、首先我想表达的是子进程结束后会产生一个信号SIGCHLD 可以用信号捕捉做一些操作。
2、第二点是关于fork(分支)的理解,父子进程的顺从有处理器调度决定,有可能父亲先消亡,有可能子进程先消亡。vfork可以理解为子进程先消亡
3、关于fork的机理以及 fork返回值我想参考下面的链接会好很多https://www.cnblogs.com/coolgestar02/archive/2011/04/28/2032018.html