码迷,mamicode.com
首页 > 系统相关 > 详细

linux C进程

时间:2020-01-11 14:52:38      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:code   lin   选择   size   col   返回   str   情况   print   

  • 一个典型的例子
#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\n");
    }
    else if(pid==0)
    {
        sleep(2);
        printf("I‘m the child %d\n",pid);
        pid2 =getpid();
        printf("I‘m the child %d\n",pid2);
        strcpy(str,"lovecpc");
        var++;
    }
    else
    {
        pid2=getpid();
        printf("I‘m the parent is %d, the child is %d\n",pid2,pid);
        strcpy(str,"wantcpc");
        wait(NULL);
        printf("complete\n");
    }
    printf("str is %s, straddr = %p, var=%d, varaddr=%p \n",str,str,var,&var);
}

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

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

  • 如果让子进程执行其他命令,exec函数族将是一个很好的选择

linux C进程

标签:code   lin   选择   size   col   返回   str   情况   print   

原文地址:https://www.cnblogs.com/saintdingspage/p/12179699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!