加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

linux编程|fork函数讲解

发布时间:2020-12-13 20:14:11 所属栏目:PHP教程 来源:网络整理
导读:[root@slave bdkyr]# cat fork_test.c /* * create by bdkyr * date 2015⑴⑵2 */ #include stdlib.h #include stdio.h #include errno.h #include unistd.h #include stdarg.h #include string.h #define MAXLINE 4096 /* max line length */ int glob = 6;

[root@slave bdkyr]# cat fork_test.c

/*

*  create by bdkyr

*  date 2015⑴⑵2

*/

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>

#define MAXLINE 4096   /* max line length */

int glob = 6;
char buf[]= "a write to stdout ";

void err_sys(const char *fmt,...);
static void err_doit(int,int,const char *,va_list);

int main(void){
        int var;
        pid_t pid;
        var = 88;
        if (write (STDOUT_FILENO,buf,sizeof(buf) ⑴) != sizeof(buf)⑴)
                err_sys("write error");
        printf("before fork ");
        if((pid = fork()) < 0){
                err_sys("fork error");
        }else if(pid == 0){
                glob++;
                var++;
        }else{
                sleep(2);
        }
        printf("pid=%d,glob = %d,var = %d ",getpid(),glob,var);
        exit(0);
}

void err_sys(const char *fmt,...){
        va_list ap;
        va_start(ap,fmt);
        err_doit(1,errno,fmt,ap);
        va_end(ap);
        exit(1);
}

static void err_doit(int errnoflag,int error,const char *fmt,va_list ap){
        vsnprintf(buf,MAXLINE,ap);
        if(errnoflag)
                snprintf(buf+strlen(buf),MAXLINE-strlen(buf),": %s",strerror(error));
        strcat(buf," ");
        fflush(stdout);
        fputs(buf,stderr);
        fflush(NULL);
}
[root@slave bdkyr]# gcc fork_test.c -o fork_test
[root@slave bdkyr]# ./fork_test                 
a write to stdout
before fork
pid=5209,glob = 7,var = 89
pid=5208,glob = 6,var = 88

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读