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函数族将是一个很好的选择
原文地址:https://www.cnblogs.com/saintdingspage/p/12179699.html