关于fork的个人理解

本文探讨了fork操作的细节,包括子进程结束后产生的SIGCHLD信号及其处理,以及父子进程执行顺序的不确定性。同时,提到了vfork与fork的区别,指出vfork可能导致子进程先结束。对于更深入理解fork的机理,推荐参考相关链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下所示:

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值