zoukankan      html  css  js  c++  java
  • linux C进程

    • 一个典型的例子
    #include <stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<unistd.h>
    #include<sys/types.h>
    int main()
    {
        pid_t pid;
        pid_t pid2;
        int var =88;
        char *str=(char*)malloc(sizeof(char)*10);
        memset(str,0x00,10);
        pid=fork();
        if(pid<0)
        {
            fprintf(stderr,"fork failed
    ");
        }
        else if(pid==0)
        {
            sleep(2);
            printf("I'm the child %d
    ",pid);
            pid2 =getpid();
            printf("I'm the child %d
    ",pid2);
            strcpy(str,"lovecpc");
            var++;
        }
        else
        {
            pid2=getpid();
            printf("I'm the parent is %d, the child is %d
    ",pid2,pid);
            strcpy(str,"wantcpc");
            wait(NULL);
            printf("complete
    ");
        }
        printf("str is %s, straddr = %p, var=%d, varaddr=%p 
    ",str,str,var,&var);
    }

    通过fork执行的流程显示,子进程会执行和父进程一样的命令,例如执行最后的printf,一般情况下fork()函数返回一个整型值,通过判断这个值程序员会知晓:pid>0是父进程代码的状态行为,pid==0是子进程的执行行为,pid<0进程创建失败

    无论如何,子进程大体上执行了和父进程几乎一样的命令(除了pid>0或pid==0条件语句中执行的部分不同)

    • 如果让子进程执行其他命令,exec函数族将是一个很好的选择
  • 相关阅读:
    Hive_元数据配置到MySQL
    第一篇
    mysql查询结果添加序列号
    java中正则表达式
    java位运算
    正数负数原码,反码,补码
    各进制间相互转换
    linux下默认安装jdk路径查找
    localhost:8080/manager/status无法访问403 Access Denied
    Idea官网指南
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12179699.html
Copyright © 2011-2022 走看看